Home >Backend Development >PHP Tutorial >Using Relative Date Helpers in Laravel's Query Builder
Laravel version 11.42 introduces a set of practical relative date query builder methods, simplifying date-related query logic. While there is no need to refactor all applications to use these methods, they do provide a more concise and easy-to-read advantage to the relative date logic in the model. Let's take a look at it with the example of the Article
model.
Suppose you have a scope for getting published articles with a specific status, and the published_at
date must be equal to or earlier than the current time:
use Illuminate\Database\Eloquent\Builder; use App\Models\Article; public function scopeActive(): Article|Builder { return $this->where('status', ArticleStatus::Published) ->where('published_at', '<=', now()); }
You can use this scope elsewhere in your code to limit articles to active articles only.
Article::with('user', 'category', 'tags') ->active() ->orderByDesc('published_at') ->limit(20) ->get();
Now, with Laravel 11.42, we can make a little adjustment to the scopeActive()
method to use the relative date method. The whereNowOrPast
method can match our original logic:
$this->where('status', ArticleStatus::Published) ->whereNowOrPast('published_at');
If you want to use the query builder to find articles marked Published
but are still in future, you can use whereFuture()
Method:
$this->where('status', ArticleStatus::Published) ->whereFuture('published_at');
What if you want to find articles that are earlier or later than today's date? The new relative date helper functions include or
and not
variants:
$this->whereAfterToday('published_at') ->orWhereBeforeToday('published_at');
For all new relative date methods added in Laravel v11.42, check out Pull Request #54408. These methods are located in a new feature called BuildsWhereDateClauses
.
The above is the detailed content of Using Relative Date Helpers in Laravel's Query Builder. For more information, please follow other related articles on the PHP Chinese website!