Laravel - Model filter date field by month

edica picture edica · Mar 9, 2018 · Viewed 9.9k times · Source

I have a method that can receive a parameter of "month" and another of "year", you can receive both or only one of them.

In the case of only receiving the month I want to make a query that I look for in a field that is called "created_at" just looking for the month of that field date

At the moment I use this code but when doing a like it does not do it correctly

        else if ($request->has('month')) {
        $month = $request->input('month');
        $currentTimestamp = date_create_from_format('n', $month)->getTimestamp();
        $currentDate = date('m', $currentTimestamp);
        $filters['updated_at'] = $currentDate;
        unset($filters['month']);
    }

        $cars = Car::where(function($query) use($filters) {
        foreach ($filters as $column => $value) {
            if ($column === 'updated_at') {
                $query->where($column, 'LIKE', '%'.$value.'%');
                continue;
            }
            $query->where($column, 'LIKE', '%'.$value.'%');
        }
    })->orderBy('updated_at', 'desc')->get();

Answer

AddWeb Solution Pvt Ltd picture AddWeb Solution Pvt Ltd · Mar 10, 2018

You should try this:

if ($request->has('month')) {
   $month = $request->input('month');
   Car::whereRaw('MONTH(created_at) = '.$month)->get();
}