Support the ongoing development of →
posted 9 years ago
Last updated 1 year ago.

Instead of making multiple joins everywhere in your project, define a relationship.
This is a nice example of a Many-to-Man relationship.

class Item...
public function likers(){
return $this->belongsToMany('User', 'likes_table');

Use the relationship to retrieve users for the item.

$usersWhoLikeThisItem = $item->likers()->get();

or the shortcut form

$usersWhoLikeThisItem = $item->likers;

You can also use eager loading to make your project faster.

$newItems = Item::with('likers')->where('created_at', '>', $time)->get();
foreach($newItems as $newItem)
  $likers = $newItem->likers;//already loaded
  foreach($likers as $user){
    echo 'PictureLink:'.$user->profile_picture_url.'<br/>';
Last updated 1 year ago.

Sign in to participate in this thread!


Your banner here too?

amilajack amilajack Joined 19 Jul 2014


We'd like to thank these amazing companies for supporting us

Your logo here?

The Laravel portal for problem solving, knowledge sharing and community building.

© 2023 - All rights reserved.