DolDurma
DolDurma

Reputation: 17311

Laravel getting Posts based on Roles of users

in my database structure each Category belongs to a user or multiple Users, each user belongs to a Role or multiple roles, and then each user have a Post or multiple posts which this model belongs to Category,

tip: Category not belongs to Role model

simply we can get posts or categories from this structure but i want to get all posts based on users specific role and fetching this posts belong to which categories

my implemented code is not correct and that return empty list:

$posts = Category::whereHas('users', function ($query) {
    $query->with(['user'=>function($q){
        $q->with(['roles'=>function($u){
            $u->whereLabel('is-admin');
        }]);
    },'posts']);
})->get();

Upvotes: 0

Views: 892

Answers (1)

user3532758
user3532758

Reputation: 2271

Edit:

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');
})->with('category')->get();

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) {
    $query->whereLabel('is-admin');
}])->with('categories')->get();
//OR
Post::whereHas('user.roles', function ($query) {
    $query->whereLabel('is-admin');
})->with('categories')->get();

Upvotes: 2

Related Questions