问题
I need to grab this month data for user in database so I write:
dd($user->products->where('paid',1)->where('created_at','>=', Carbon::now()->startOfMonth()->toDateString())->all());
and I got 0 results...
When I try Carbon::now()->subMonth() its works good but return me last 30 days ...
How I can solve this? How to get only this month data ?
回答1:
->toDateString() is causing the query to look for a string value, and not a date. There's two ways to solve this:
(...)->where('created_at', '>=', Carbon::now()->startOfMonth())
// OR
(...)->whereDate('created_at', '>=', Carbon::now()->startOfMonth()->toDateString())
If you just use a Carbon variable, Laravel knows to check for date logic. Alternatively, if you're using a string, you can override the where logic to treat it as a date by using ->whereDate()
来源:https://stackoverflow.com/questions/50473220/laravel-carbon-return-me-0-results