Paolo Resteghini
Paolo Resteghini

Reputation: 432

Laravel Select records in specific year

I'm new to Laravel and struggling to identify how I can select all records created in 2015 using the created_at field provided by the timestamp.

The model I am using is Blog:

$posts = Blog::latest()->get();

Example date in database:

2015-01-25 12:53:27

Could anyone shed some light?

Thanks!

Upvotes: 16

Views: 40209

Answers (4)

Ronon
Ronon

Reputation: 842

Just for completion. There is the Laravel method whereYear() for it:

Blog::whereYear('created_at', 2017)->get();

The method whereYear() was introduced in Laravel 5.3 (August 2016), documented under the subsection "Additional Where Clauses" together with whereDate() / whereMonth() / whereDay() / whereYear() etc.

Upvotes: 42

Abraham Nzau
Abraham Nzau

Reputation: 309

Scope function worked perfectly for me:

class Blog extends Eloquent {
    public function scopeSeason($query,$year)
    {
        return $query->whereYear('created_at', '=', $year);
    }
}

Usage:

$blog = Blog::where('status','active')->season(2021)->get();

Upvotes: 1

Keerthivasan
Keerthivasan

Reputation: 21

You can use the scope method in your model.

Model:

class Blog extends Eloquent {
    public function scopePopular($query, $year)
    {
        return $query->where('year', '=', $year);
    }
}

Usage:

$blog = Blog::popular(1999)->get();

Upvotes: 2

mcklayin
mcklayin

Reputation: 1360

You can do it like that: $posts = Blog::where( DB::raw('YEAR(created_at)'), '=', '2015' )->get();

Here you can get year from created_at field with YEAR function, then compare with your date.

Upvotes: 9

Related Questions