Home > Mobile >  How to get current month record in laravel?
How to get current month record in laravel?

Time:11-24

Need to get record of current month but query return the wrong result.There is only one record in db.but i get wrong count for the current month

$data = UserData::select(
    DB::raw("count(phone) as total")
)
    ->whereMonth('creation_date', Carbon::now()->month)
    ->get();
return view('kpidata', compact('data'));

this is result of mysql query enter image description here

and this is the result i get using laravel queryenter image description here

CodePudding user response:

"whereMonth" compares only the month number not the year

Option 1:

UserData:select(DB::raw("count(phone) as total"))
    ->whereBetween('creation_date', 
        [
            Carbon::now()->startOfMonth(), 
            Carbon::now()->endOfMonth()
        ])
    ->get();

Option 2:

UserData:select(DB::raw("count(phone) as total"))
    ->whereYear('creation_date', Carbon::now()->year)
    ->whereMonth('creation_date', Carbon::now()->month)
    ->get();

CodePudding user response:

Here Item is a modal.

$data = Item::select('*')
            ->whereMonth('created_at', Carbon::now()->month)
            ->get();
   
print_r($data);

CodePudding user response:

You actually need a full date by using the whereMonth and not just the integer equivalent of the month.

$data = UserData::whereMonth('creation_date', Carbon::now())->get();

return view('kpidata', compact('data'));

Also, if you just want to display the recordcount, you can just do:

$data = UserData::whereMonth('creation_date', Carbon::now())->count();
  • Related