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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With