seema patil
seema patil

Reputation: 61

implode function return implode(): Invalid arguments passed

I am implode some id, it works when array have at least 1 value. if array is null the implode function returns error as implode(): Invalid arguments passed

$arr=implode(',', $request->id);


 $product= DB::table('sub_categories')
        ->join('categories','sub_categories.category_id','=','categories.category_id')
        ->join('products','sub_categories.subcategory_id','=','products.subcategory_id')
         ->join('colors','colors.color_id','=','products.product_color')
         ->select('products.*','categories.category_name','sub_categories.subcategory_name','colors.*')
         ->whereRaw('color_id IN ('.$arr.')')
         ->where(strtolower('sub_categories.subcategory_slug'),$request->subcategory_id) 
        ->orderBy('products.product_name','ASC')
        ->get();

Upvotes: 0

Views: 210

Answers (2)

Donkarnash
Donkarnash

Reputation: 12835

Try with a default value to account for scenario when $request->id is null

$arr = implode(',', $request->input('id', []));

Can do the whereIn conditionally in the query


```php
$arr=implode(',', $request->input('id', []));


 $query= DB::table('sub_categories')
        ->join('categories','sub_categories.category_id','=','categories.category_id')
        ->join('products','sub_categories.subcategory_id','=','products.subcategory_id')
         ->join('colors','colors.color_id','=','products.product_color')
         ->select('products.*','categories.category_name','sub_categories.subcategory_name','colors.*')
         ->where(strtolower('sub_categories.subcategory_slug'),$request->subcategory_id);

if(!empty($arr)) {    
    $query->whereRaw('color_id IN ('.$arr.')');
}

$product = $query->orderBy('products.product_name','ASC')->get();

Upvotes: 1

STA
STA

Reputation: 34678

If the given data is not an array, then implode() function will throw a warning error. To get rid of the error, you can check the array with is_array() method:

if(is_array($request->id)){
   $arr = implode(',', $request->id);
} else {
   $arr = NULL;
}

Upvotes: 1

Related Questions