12

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!

4 Answers 4

34

Just for completition. There is a Laravel method for it.

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

See where clause, subsection whereDate / whereMonth / whereDay / whereYear

1
  • This should be accepted solution...
    – DokiCRO
    Aug 30 at 9:48
9

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.

1
2

You can use scope function in your model. Eg:

Your Model

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

Usage

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

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();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.