Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GastonUy's avatar

Query builder - filter by date (+ x days > today)

In my example I have Flight and Airport models. Airport has many Flights and Flight belongs to Airport.

Airport has an integer attribute called daysAfterFlightLanded, which I use to know how many days after a Flight landed I want to show it in results. Flight has datetime attribute called landed_at.

I need to retrieve all Flights (preferably with query builder) that has not landed yet and those which has landed but summing daysAfterFlightLanded is greater than today.

I do not know how to implement this sum at the query. Hope I'm being clear. Thanks in advance.

0 likes
5 replies
GastonUy's avatar

Thanks but not what I'm looking for @colourmill .

What I am trying to do is retrieve records (with Eloquent or query builder) filtering by (date attribute + days attribute from related record) > Carbon::now().

colourmill's avatar

@GastonUy Oh I see now… sorry, I misread it. You'll most likely have to work with a stored function for that (http://www.mysqltutorial.org/mysql-stored-function/). From by brief experiences with them, they're not extremely pleasant to work with, but your example seems simple enough that it shouldn't be too much of a hassle.

Alternatively, you could do an optimistic selection where you select the flights that could be relevant, and then filter the results through the handy collection methods.

You'll end up with something like this:

$flights = Flight::where('has_landed', '=', 1)->get(); // You'll want to add a date range or something to lower the returned results
$flights->filter(function ($flight) {
    return $flight->daysAfterFlightLanded + $flight->landed_on > now;
});
1 like

Please or to participate in this conversation.