0
votes

I am using laravel 5.1 for a CMS development. I have a simple structure of posts, users and users can like posts.

Posts and Users have many-to many relationship and use a pivot table for relationship.

Posts Model has

public function likedby()
{
    return $this->belongsToMany('App\Models\User','user_like_post')
        ->withTimestamps();
}

User Model has

public function likes(){
    return $this->belongsToMany('App\Models\Post','user_like_post')
        ->withTimestamps();
}

I want to list the latest activity of the users. For e.g.

  1. Username1 likes Post2
  2. Username5 likes Post9
  3. Username30 likes Post25

I know I have to write an sql query like this -

mysql > select users.name, posts.heading from user_like_post as ulp 
      > join users on ulp.user_id=users.id 
      > join posts on ulp.post_id=posts.id 
      > order by ulp.created_at desc limit 10;

The above query works fine but is there a way to do it using laravel eloquent?

1

1 Answers

2
votes

If you want pure eloquent solution, then you need additional model for the pivot table:

class PostUser extends Model {
  protected $table = 'user_like_post';
  public function post()
  {
    return $this->belongsTo(Post::class);
  }

  public function user()
  {
    return $this->belongsTo(User::class);
  }
}

// then something like this
$activity = PostUser::latest()->take(10)->get();

@foreach ($activity as $action)
  {{ $action->user->name }} likes {{ $action->post->title }}
@endforeach

Other than that you would need joins in order to sort the results by pivot table.