4 months ago

Query with attributes from related model

Posted 4 months ago by mleontenko

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

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?

Please sign in or create an account to participate in this conversation.