I need to construct query using whereBetween
clause, but with a twist for which i didn't find a answer applicable in my case. I need, for when from
parameter isn't present to regard that as to query from beginning. If to
parameter isn't present, then needs to look everything after previously mentioned parameter.
Query currently:
Vehicle::whereBetween("updated_at", [$dates->start_date, $dates->end_date])->with("something")->get();
How i wanted it to be:
Vehicle::whereBetween("updated_at", "lookup from start date if present, if not, look from beginning", "lookup to said end date if it's present, if not, look up till the end"])->with("something")->get();
I am asking, what is appropriate to put in, when parameter isn't present so it works in way i described?
Edit:
If omitted, start date, query works fine. If end date gets omitted, query return zero in best case scenario. Worst case, throws an error.
I tried putting null
, empty string, false, zero(0), for end date, nothing works.
CodePudding user response:
It would make more sense to not use whereBetween
and simply add where
clauses conditionally. You could do this with the when() method:
Vehicle::with("something")
->when($dates->start_date, function ($query, $date) {
$query->where('updated_at', '>=', $date);
})
->when($dates->end_date, function ($query, $date) {
$query->where('updated_at', '<=', $date);
})
->get();