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

stephen waweru's avatar

whereIn query return an empty array laravel 8

upon clicking a filter i want show all the products associated to the filter.i have created a filter array whereby some products are associated to that filter.i am using jquery to show the products and have successfully achieved selecting the filter in jquery and calling a function using ajax.the issue comes in the controller where am calling the function to show the products.am using explode to combine the filters then implode them in to an array.then i have passed the array to a function that selects shows the products.here is my function

if(isset($request->fabric)){

       $explodefabric = explode(',',$request->fabric);

       $implodefabric = implode(",",$explodefabric);

       //dd($implodefabric);die();
       
        $categoryproducts = DB::table('merchadises')
        ->whereIn('fabric',$implodefabric)
        ->get();

       dd($categoryproducts);die();

       return response()->json($categoryproducts);
       return view('frontend.product.productsjson',compact('events','url','categoryproducts'));
    }

am getting an empty array and it doesnt show the products associated to the filter selected.where might i be going wrong on my code.

0 likes
7 replies
tykus's avatar
tykus
Best Answer
Level 104

Why do you implode - you are making a comma-separated string where an array is needed by the whereIn method. Assuming the $request->input('fabric') is a string; then explode is necessary:

$categoryproducts = DB::table('merchadises')
    ->when(
        $request->input('fabric', false),
        fn ($builder, $fabric) => $builder->whereIn('fabric', explode(',', $fabric))
    )->get();

Using the when Builder method - you can get rid of the isset() check as well.

2 likes
tykus's avatar

@stephen waweru when Builder method passes the first argument into the Closure.

1 like

Please or to participate in this conversation.