Laravel Laravel, how to fetch records created within the month?

This post is about Laravel database queries and date format using Carbon, a PHP API extension for DateTime.

Ish Sookun

1 min read min read

Today, I found this tip published by @TheLaravelDev on Twitter. It's a handy piece of code that will allow you to fetch the records created between the start and the end of the month using Carbon in your Laravel project.

// Define scope within your model
public function scopeThisMonth(Builder $query): Builder
{
    $startDate = Carbon::now()->startOfMonth();
    $endDate = Carbon::now()->endOfMonth();
    return $query->whereBetween('created_at', [$startDate, $endDate]);
}

// Use the scope like below
Product::query()->thisMonth();

Laravel documentation

The whereBetween method verifies that a column's value is between two values.

$users = DB::table('users')
           ->whereBetween('votes', [1, 100])
           ->get();

Read more on this.

For more interesting tips on Laravel you can follow @TheLaravelDev.