模型

时间:2016-04-03 16:32:07

标签: php laravel laravel-5 eloquent

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

2 个答案:

答案 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

相关问题