You do a find on the role and then collect it from the relations.
If you only want the posts you can do it with (not tested):
$posts = Post::whereHas('user', function (Builder $userQuery) use ($id) {
$userQuery->whereHas('roles', function (Builder $rolesQuery) use ($id) {
$rolesQuery->where('id', $id);
});
})->get();
See: https://laravel.com/docs/5.8/eloquent-relationships#querying-relationship-existence
Hi CreedMaicc
I think you need hasManyThrough instead of hasMany,
Watch Jefrey Way in this video: https://laracasts.com/series/eloquent-relationships/episodes/4
We are basically looking for a Role_Id through Post which belongs to a User.
$roles = App\Post::whereRoleId('some_id')->first();
$roles->posts;
and you get all the post with that role_id
It is just a idea,
Best, -Lucas Oliveira.
Hi CreedMaicc,
As far as I understood you want to grab the Post Where the creator User has a Role_Id == ?,
So I did this:
roles table
users table
posts table
=>then on Role model I did this,
protected $fillable = [
'role',
];
public function posts(){
return $this->hasManyThrough(Post::class, User::class);
/* You do not need to provide id or foreign key, if you using the default incremented id on the Schema::, and also you do not even to have in your database for this to work */
}
=>on User I have:
public function posts()
{
return $this->hasMany(Post::class, 'user_id');
}
=>and on Post I have:
public function user()
{
return $this->belongsTo(User::class);
}
=>Now you can say:
$roles = App\Role::find(role_id)->posts
You get all the Post a User wrote with this specific Role Id
Furthermore, you can say:
$roles->first()->user
And you will have such User. This was what I was saying less typing, much clean, and powerful.
I hope that helps.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community