Reputation: 58652
I'm trying to query all my visitor for the last one year.
I've tried
$raw = Visitor
::whereDate('created_at','>', Carbon::now()->year-1)
->get()
->pluck('created_at');
Note:
Carbon::now()->year-1 //-------------> 2018
I keep getting all the vsiitors in my db.
What did I do wrong ?
Upvotes: 2
Views: 3146
Reputation: 14241
Try it like this:
$raw = Visitor::select('created_at')
->whereDate('created_at','>', now()->subYear())
->get();
Notice that here I replaced the part ->get()->pluck('created_at')
with select('created_at')
because you only want the values of that column. Your approach would get all the results in memory and then pluck the wanted values, the alternative just brings you your desired elements.
Upvotes: 5
Reputation: 2331
You could simply use whereYear
for that.
$data = User::query()
->whereYear('created_at', now()->year -1)
->get()
->pluck('created_at');
whereYear - method may be used to compare a column's value against a specific year.
Upvotes: 1
Reputation: 1556
try this code :
$raw = Visitor::whereDate('created_at','>', Carbon::now()->addYears(-1))->get()->pluck('created_at');
Upvotes: 1
Reputation: 3341
$raw = Visitor::whereDate('created_at','>', Carbon::now()->subYear())->get()->pluck('created_at');
When you do Carbon::now()->year - 1
, it returns 2018
.
So the comparison is done like this: 2019-09-15 18:18:00 > 2018
Upvotes: 2