【问题标题】:Laravel current user in modelLaravel 模型中的当前用户
【发布时间】:2016-07-23 03:09:31
【问题描述】:

我需要在我的模型中获取Auth::id() 以检查当前用户是否已投票。如何在 Eloquent 模型中访问当前用户?

型号: 命名空间应用程序;

use App\User;
use App\ArticleVote;
use Illuminate\Database\Eloquent\Model;

class Article extends Model {
  protected $fillable = ['title', 'body', 'link'];
  protected $appends = ['votesCount', 'isUserVoted'];

  public function getIsUserVotedAttribute() {
    return !!$this->votes()->where('user_id', \Auth::id())->first();
  }
}

getIsUserVotedAttribute 方法中我得到\Auth::id() 为null

【问题讨论】:

  • 你的意思是你得到 id OR null 吗?
  • 向你展示这个类中的 import pat
  • 更新问题。我得到空
  • 如果您这样做,您只需将\Auth::id() 更改为\Auth::user()->id。或者您可以在没有 Auth 外观的情况下全局使用以下内容:auth()->user()->id

标签: php laravel laravel-5 eloquent


【解决方案1】:

可以在模型内部使用Auth::user()获取当前用户。

use Illuminate\Support\Facades\Auth;

/*
 example code: adjust to your needs.
*/
public function getIsUserVotedAttribute()
{
    $user = Auth::user();
    if($user) {
        // using overtrue/laravelFollow (for this example)
        return $user->isVotedBy($this) // this is just an example, do whatever you wanted to do here
    }
    return false
}

(laravel version 5.7)

【讨论】:

    【解决方案2】:

    如果您打算在 controller 中创建 Acticle 的实例后调用方法 getIsUserVotedAttribute(),如下所示:

    $article = new Article;
    $article->getIsUserVotedAttribute();
    

    我建议您在定义method 时将user id 作为参数传递,这样

    public function getIsUserVotedAttribute($user_id) {
         return !!$this->votes()->where('user_id', $user_id)->first();
    }
    

    然后你可以像这样在你的控制器中使用它

    $article = new Article;
    $article->getIsUserVotedAttribute(Auth::user()->id);
    

    希望对你有帮助

    【讨论】:

    • 不幸的是我不能这样做,因为我使用 Transformers 返回 JSON 并且我在控制器中的索引方法看起来像这样 return $this->response->withPaginator(Article::orderBy('id', 'desc')->paginate(15), new ArticleTransformer, 'articles');
    猜你喜欢
    • 2021-10-28
    • 1970-01-01
    • 2016-04-06
    • 2018-11-09
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多