Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent if variable exists query on it

I have a form with two optional fields, the date and the location. If the user chooses either of these the query uses the field they choose in addition to the required fields. Is there a way to use eloquent so if the variable has value use it in the query and if not ignore it. I know I can use several if statements, but am wondering if there is a more efficient way.

like image 208
Aaron Avatar asked Jan 24 '26 13:01

Aaron


1 Answers

Yes there is , you can do like below. Just chain the condition when it has value from POST

$query = Item::where(id,$id);

if ($request->date) {
    $query->where(date,$request->date);
}

if ($request->location) {
    $query->where(location,$request->location);
}

$items = $query->get();
like image 117
sumit Avatar answered Jan 27 '26 04:01

sumit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!