Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mleontenko's avatar

Query with attributes from related model

I have a Post model that can have multiple categories:

The relationship looks like this:

public function categories()
    {
        return $this->hasMany('App\PostsCategories', 'post_id', 'id');
    }

PostsCategories table contains IDs of posts and their categories.

I'm trying to query posts by multiple criteria (post name, category, etc.) like this:

public function search(Request $request)
{   
    $post_name= $request->post_name;
    $category_id= $request->category_id; // value is integer 1- 20

    $posts= Post::query()
            ->where('post_name', 'LIKE', "%{$post_name}%")
            // and where category equals $category_id
            ->paginate(50);
}

I'm having trouble with figuring out how to add category to my query. How can I include attributes form related models in my query?

0 likes
3 replies
MichalOravec's avatar
Level 75

@mleontenko

$posts = Post::where('post_name', 'LIKE', "%{$post_name}%")->whereHas('categories', function($query) use ($category_id) {
    $query->where('id', $category_id);
})->paginate(50);

Documenation: https://laravel.com/docs/7.x/eloquent-relationships#querying-relationship-existence

But I think that your logic is wrong.

Post belongs to Category, so post should have a category_id

Another things are Tags, Post could have many Tags, and Tags could have many posts.

In that case it's many to many relationships.

But that code above will work.

1 like
Rayray's avatar

if i were you i would do something like this

posts model

use App\Postcategory;

public function postcategories() { return $this->hasMany(PostsCategory::class); }

this means you have a single post that has multiple categories

Then to access all the post categories in a post

you can state like $posts = Post::all(); foreach($posts as $post){ foreach($post->postcategories as $postcat){ $postcat->title } //this will give you a title of the category

}

i guess you want to foreach all posts that has that category.

Am also stuck now.....

1 like
mleontenko's avatar

@michaloravec Thanks, that will work!

I used Post - Category analogy only for example, my app has entirely different classes that would be harder to explain. It's true this logic would be wrong in Posts and Categories case...

Please or to participate in this conversation.