Search code examples
phplaravellaravel-5php-carbon

How do I use whereYear inside filter Laravel


I have a collection that I am trying to filter on created_at year. Laravel 5.3. I am trying to use whereYear inside my filter but it's sqwaking that the method is undefined. How do I define it? Or is there a better way?

      $datas = Campaign::all();

      if($request->year) {
         $value = $request->year;
         $datas = $datas->filter(function($data) use ($value) {
             return $data->created_at->whereYear($value);
         });
       }

Solution

  • I would do this more compact:

    So in your Controller you can do:

    $datas = ($request->year)
           ? Campaign::inYear($request->year)->get()
           : Campaign::all();
    

    The advantage is, that you get only the record that you need from the DB, and don't have to do any kind of filter on a Collection. This will also increaser your performance a little bit.

    In your Campaign Model you add on inYear scope that is than reusable:

    use Carbon\Carbon;
    
    class Campaign extends Model
    {
        public function scopeInYear($query, $year)
        {
            return $query->whereBetween('created_at', [
                Carbon::create($year)->startOfYear(),
                Carbon::create($year)->endOfYear(),
            ]);
        }
    }