[英]Laravel current user in model
我需要在模型中獲取Auth::id()
才能檢查當前用戶是否已投票。 如何在口才模型中訪問當前用戶?
型號:命名空間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
如果您打算在像這樣的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);
希望能幫助到你
您可以在模型內部使用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
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.