I searched a lot but could not find any answer about it, so I hope you could help me!
I have three tables: posts, users and post_users.
Post_users contains two columns: user_id and post_id.
I need to get all posts by an user with Eloquent. Any ideas?
Advertisement
Answer
Model User:
public function posts()
{
return $this->belongsToMany('AppPost', 'post_users', 'user_id', 'post_id');
}
Model Post:
public function users()
{
return $this->belongsToMany('AppUser', 'post_users', 'post_id', 'user_id');
}
Try:
$user = User::find($id); $allpost = $user->posts()->get(); var_dump($allpost);