skip to Main Content

I have a post table that has a many to many relationship with a category table, and of course a pivot table between both.

I’m trying to get all posts that match exactly with an array of categories, example:

category_array = [food, travel, people]

So, i want all post that have all those categories inside.

I tried this but didn’t work.

 $query->when(
            $filters['category'] ?? false,
            function ($query, $category) {
             $query->whereHas('categories', function ($query) use($category){
                    $query->whereIn('name', $category);
                    
                });
            }
        );

It just retrieved posts which have one of them.

I expecting only post that have all of the categories. Not just one.

Update I tried this approach, but didn’t work as well:

  $query->when(
            $filters['category'] ?? false,
            function ($query, $categories) {
                $query->whereHas('categories', function ($query) use ($categories) {
                    foreach ($categories as $cater) {
                        $query->where('name', $cater);
                    }
                });
            }

        );

2

Answers


  1. You need to build a nested query with a loop on your array to put all your categories in where with and like this:

    function ($query, $category) {
                 $query->whereHas('categories', function ($query) use($category){
                        for($categories as $category){
                            $query->where('name', $category);
                        }
                        
                    });
                }
    
    Login or Signup to reply.
  2. You add an extra condition to whereHas that determine the count of categories relationship have to be equal the count of $categories array

    $query->when(
        $filters['category'] ?? false,
        function ($query, $categories) {
            $query->whereHas('categories', function ($query) use ($categories) {
                $query->whereIn('name', $categories);
            }, '=', count($categories));
        }
    
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search