How to filter Model records with created_date in Laravel

Categorized as Laravel Tagged

Often times you need to filter your Model records based on the created_date field. With Laravel, you can make scope Methods after() and before() and use them like below.

// in Post.php

public function scopeAfter(Builder $query, string $date): Builder
{
	return $query->where($this->qualifyColumn('created_at'), '>=', $date . ' 00:00:00');
}
public function scopeBefore(Builder $query, string $date): Builder
{
	return $query->where($this->qualifyColumn('created_at'), '<=', $date . ' 23:59:59');
}


// Usage

Post::query()
	->active()
	->after('2022-02-28')
	->before('2022-03-31')
	->get();

In case multiple of your Models needs these methods, you can move them to Trait.

Leave a reply

Your email address will not be published. Required fields are marked *