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
4
Answers
"whereMonth" compares only the month number not the year
Option 1:
Option 2:
Here Item is a modal.
You actually need a full date by using the
whereMonth
and not just the integer equivalent of the month.Also, if you just want to display the recordcount, you can just do:
Avoid using
whereMonth()
and similar "helper" methods. They are a dreadful habit and lead to unnecessarily inefficient queries. This may not matter when testing on your local machine, but if you are fortunate enough to get your application into the "wild" and it is successful with 1,000s of concurrent users, it may be the difference between success and failure.Your code –
will result in a query that looks something like –
Because of the
month()
function wrapped aroundcreation_date
the server is unable to use any available index oncreation_date
. It is also unnecessarily executing the function for each row. Read more about Non-SARGable Predicates.As already suggested by @Heroherm, you should use
whereBetween()
–which will result in a query that looks something like –
If this does not work, as previously suggested, please use
->dd()
in place of->get()
to see what is going on.