Laravel get current month data example; In this tutorial, you will learn how to get current month records in laravel application. Laravel gives us more then eloquent queries for showing or adding records in database. Gettings months records we can use whereMonth or where raw queries as well.
Fetching current month and current year record in laravel application we can use the below examples. let’s see the easy and simple way to use and get the current month records from database in laravel.
Example 1: Using Laravel whereMonth
If you want to get specific year month record in laravel then use the below code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Carbon\Carbon;
class UserController extends Controller
{
public function index()
{
$users = User::whereYear('created_at', Carbon::now()->year)
->whereMonth('created_at', Carbon::now()->month)
->get();
dd($users);
}
}
Example 2: Using Raw Query
We can use the whereRaw query as well.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Carbon\Carbon;
class UserController extends Controller
{
public function index()
{
$currentMonth = date('m');
$users = User::whereYear('created_at', Carbon::now()->year)
->whereRaw('MONTH(created_at) = ?',[$currentMonth])
->get();
dd($users);
}
}
I hope these example help you..