Laravel 5 - Verification that the user "voted" when returning all votes for the resource as a relation

I am creating a voting system for the link exchange site I'm working on.

When the user votes for the link, as a new line is added in db with the link id and user id.

When showing these links in the controller, I call the connection (of votes):

$links = Link::orderBy('created_at', 'desc')->with('votes')->paginate(20); 

And the ratio in the model

 public function votes() { return $this->hasMany('\App\LinkVote'); } 

In my opinion, I run foreach on $ links to display each of them. My goal is to show another button if the user has already voted for this link.

When dd'ing $ link-> votes I get:

enter image description here

How can I check (in my view and in foreach) if the current registered user is in this array of votes?

+5
source share
1 answer

You can try contains() :

 $link->votes->contains('user_id', auth()->user()->id); 

Or where() with count() :

 if ($link->votes->where('user_id', auth()->user()->id)->count()) { 
+5
source

Source: https://habr.com/ru/post/1259531/


All Articles