code-8
code-8

Reputation: 58652

Query last one year - Laravel 5.8

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

Answers (4)

Kenny Horna
Kenny Horna

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

tempra
tempra

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.

see more

Upvotes: 1

Ahmed Atoui
Ahmed Atoui

Reputation: 1556

try this code :

$raw = Visitor::whereDate('created_at','>', Carbon::now()->addYears(-1))->get()->pluck('created_at');

Upvotes: 1

fonini
fonini

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

Related Questions