Laravel getting Posts based on Roles of users


I’ve tested the second solution and it seems to be working just fine. I did bring one minor change; that is change categories to category. Here is the updated code:

$posts = Post::whereHas('user.roles', function($q){
    return $q->whereLabel('is-admin');

I assumed your relationship definitions to be similar to the following (showing only the necessary relations):

Note before: Role and User has a many to many relationship because one user can have many roles and one role can belong to many users. Therefore a pivot table role_user sits between roles and users table to manage user roles.

In user model:

public function roles()
    return $this->belongsToMany(Role::class);

Role model:

public function users()
    return $this->belongsToMany(User::class);

Post Model:

public function user()
    return $this->belongsTo(User::class);
public function category()
    return $this->belongsTo(Category::class);

Basically user hasMany roles, and category doesn’t have anything to do with roles, and in this situation nothing to do with users either. so why not try selecting posts based on user roles and then eager load categories. Give this a try:

Post::with(['user.roles' => function ($query) {
Post::whereHas('user.roles', function ($query) {

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top