我需要在我的模型中获取Auth::id()
以检查当前用户是否已投票。如何在Eloquent Model中访问当前用户?
型号: 命名空间App;
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
答案 0 :(得分:0)
如果您计划在getIsUserVotedAttribute()
中创建Acticle
的实例后调用方法controller
,请执行以下操作:
$article = new Article;
$article->getIsUserVotedAttribute();
我建议您在定义user id
时将method
作为参数传递给
public function getIsUserVotedAttribute($user_id) {
return !!$this->votes()->where('user_id', $user_id)->first();
}
然后你就可以在你的控制器中使用它了
$article = new Article;
$article->getIsUserVotedAttribute(Auth::user()->id);
希望有所帮助
答案 1 :(得分:0)
您可以在模型内部使用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
)