vendredi 11 novembre 2016

Fetch data form pivot tables with one query using laravel eloquent

What is the best way to get the 3rd table data with one query.

User   :   id | name    
Event  :   id | user_id  
Likes  :   id | user_id | event_id

Here is my  Eloquent Query

$events = Event::with('likes','users')->get();

return view('events',compact('events'));

In views i am iterating over all events like this,
User has multiple events as well as multiple likes in relation model.


@foreach($events as $event)

 
  //show like id if it is liked by the user

     // I have to execute another loop only to check if it is liked or not 
      @foreach($row->likes as $like)

             @if(Auth::id() == $like->user_id)
                   Liked
             @endif
      @endforeach

@endforeach

Now i need to check if the logged in user has liked this event or not ? along with all the events whether they are liked or not ?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire