Support Junior
Support Junior

Reputation: 11

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?

Upvotes: 1

Views: 718

Answers (1)

Fadi Sarwat
Fadi Sarwat

Reputation: 46

Use when function provided by laravel:

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

Upvotes: 3

Related Questions