John Davidson

php - 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) {

My Answer:
>whereHas('roles', function ($query) {
$query->where('name', 'admin');

This code is trying to get all categories that have users with the role of 'admin', and then eager load the posts for those categories. However, since categories do not directly belong to roles, this code will not work as expected.

Instead, you can try the following code to achieve the desired result:

$posts = Post::whereHas('category.users.roles', function ($query) {
$query->where('name', 'admin');

This code will get all posts that belong to categories where the users have the role of 'admin'. It will also eager load the category for each post so you can access the category information as well.

Rate this post

3 of 5 based on 6043 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us