'Laravel "Skip" WhereIn when request not Filled or null?

I have controller with request like below

$product = $request->product; //array
$product_category = $request->product;

if($request->filled('product')){
    $product = product()::whereIn('product',$product)
                          ->where('product_category',$product_category)
                          ->get();
}else {
    $product = product()::where('product_category',$product_category)
                          ->get();
}

how do i skip or make the eloquent still worked if $product request was not filled or null?

Currently i used the if for that query is remove where on product, but that will make me create alot of eloquent with more request

But I think this is not the best or right think to do, what is my better option for doing that where without writing a lot of if-elseing?



Solution 1:[1]

Use when function provided by laravel:

Product::when($request->product, function($query, $product) {
        $query->whereIn($product);
 })->where("product_category", $product_category)->get();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fadi Sarwat