2

I need to get Auth::id() in my model to check if current user has voted. How to access to current user in Eloquent Model?

Model: namespace 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();
  }
}

In getIsUserVotedAttribute method I get \Auth::id() of null

4
  • Do you mean you get id OR null? Commented Apr 3, 2016 at 16:37
  • Show you import pat in this class Commented Apr 3, 2016 at 16:38
  • Updated question. I get null Commented Apr 3, 2016 at 16:44
  • If you do it this way, you just have to change \Auth::id() to \Auth::user()->id. Or you can use the following globally without the Auth facade: auth()->user()->id Commented Nov 9, 2018 at 16:52

2 Answers 2

2

You can use Auth::user() inside the model to get the current 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)

Sign up to request clarification or add additional context in comments.

Comments

1

If you plan to call the method getIsUserVotedAttribute() after creating an instance of Acticle in a controller like this:

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

I suggest that you pass the user id as parameter when defining the method such that

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

Then you can use it in your controller like this

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

Hope it helps

1 Comment

Unfortunately i cant do like this because I use Transformers to return JSON and my index method in controller looks like this return $this->response->withPaginator(Article::orderBy('id', 'desc')->paginate(15), new ArticleTransformer, 'articles');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.