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.
- Username1 likes Post2
- Username5 likes Post9
- 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?