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

iki's avatar
Level 3

many to many filter problem

i have 3 tables , colors , products and color_product with many to many relation , my problem is that i have a filter where the user can choose more than one color with the rest of the filter options how i filter the data with the selected colors, code will explain more

http://prntscr.com/l0vzim

http://prntscr.com/l0vzy8

http://prntscr.com/l0w02x

http://prntscr.com/l0w093


 public function filter(Request $request)

    {
        $sections = Section::all();
        $section = $request->section_id;
        $min = $request->min;
        $max = $request->max;
        $colors = $request->color_id;

        $products = Product::where('is_active', 1);
        if ($section)
            $products->where('section_id', $section);
        if ($min)
            $products->where('price_after', '>=', $min);
        if ($max)
            $products->where('price_after', '<=', $max);
//        if ($colors)
//            foreach ($colors as $color) {
//
//
//
////                $color = Color::where('id', $color)->first();
////                $checker = $color->product;
////                foreach($checker as $products)
//////                $products = $product->where('is_active', 1)->get();
////                if ($products->is_active == 1)
////                if ($section)
////                    $products->where('section_id', $section);
////                if ($min)
////                    $products->where('price_after', '>=', $min);
////                if ($max)
////                    $products->where('price_after', '<=', $max);
//            }

        $filter = $products->paginate(9);
 
        return view('site.filter', compact('filter', 'sections'));
    }


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
     protected  $fillable=[

             'name',
             'code',
             'price_before',
             'price_after',
             'quantity',
             'section_id',
             'category',
             'description',
             'img',
         ];

     public function color()
     {

         return $this->belongsToMany('App\Color');

     }
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Color extends Model
{
     protected  $fillable=[

             'name',

         ];

    public function product()
    {

        return $this->belongsToMany('App\Product');

    }
}

0 likes
9 replies
MikeMacDowell's avatar
Level 25

You should use a whereHas like below.

$products->whereHas('color', function($query) use ($colors) {
    $query->whereIn('id', $colors);
});

As a side note, if your relationship is returning multiple models in a collection, it's better to name them with plural names as a reminder

public function colors()
     {

         return $this->belongsToMany('App\Color');

     }
1 like
iki's avatar
Level 3

@MikeMacDowell


        if ($colors)
        {
//            $data = array();
//            foreach ($colors as $color) {
//                $color = Color::where('id', $color)->first();
//                $checker = $color->product;
//                foreach ($checker as $checked)
//                    if ($checked->is_active == 1)
//                array_push($data, $checked);
//            }
//            dd($products);
//            $products = collect($data);
            
            $products->whereHas('color', function($query) use ($colors) {
                $query->whereIn('id', $colors);
            });



        }
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select count(*) as aggregate from `products` where `is_active` = 1 and `section_id` = 2 and exists (select * from `colors` inner join `color_product` on `colors`.`id` = `color_product`.`color_id` where `products`.`id` = `color_product`.`product_id` and `id` in (4, 2)))

i can check multiple checkboxes , like multi colors , and even when i check one box i get the same error

MikeMacDowell's avatar

@iki do you have an 'id' column on your 'color_product' pivot table?

That will cause this error. Laravel assumes that pivot tables don't have an 'id' column, so you'll need to remove it, or specify the table name in the whereIn query

iki's avatar
Level 3

@MikeMacDowell it actually worked , after i removed the id column but to be honest idk what i wrote , so can u explain the code u provided to me so i understand it and dont ask the same question again please ?

1 like
iki's avatar
Level 3

@Artak that really helped thanks

iki's avatar
Level 3

there is just one thing that i dont understand , when we use whereHas('color') it brings all the products that have colors , so in the query why did we write ('id',$colors) , i mean colors is the colors id , so does that check the color id in the colors table then gets the relative products from the relation or what ? @Artak @MikeMacDowell

MikeMacDowell's avatar

@iki yes, within the whereHas closure you're querying the Color model itself, rather than the Product model.

So you're saying, give me all the Products that have a Color, but that Color must have its id in the array.

As an aside, there's also just a has() method, which will only return Products that have a Color, which is not useful in this case, but can be if you have a nullable foreign key column in a relationship.

1 like
iki's avatar
Level 3

thats create ,thanks i really learned a lot out of this

Please or to participate in this conversation.