Laravel模型中的当前用户


Laravel current user in model

我需要在我的模型中获取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()

您可以在模型中使用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

如果您计划在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);

希望它能帮助