Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Model filter date field by month

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();
like image 244
edica Avatar asked Mar 09 '18 13:03

edica


2 Answers

You should try this:

if ($request->has('month')) {
   $month = $request->input('month');
   Car::whereRaw('MONTH(created_at) = '.$month)->get();
}
like image 79
AddWeb Solution Pvt Ltd Avatar answered Nov 10 '22 06:11

AddWeb Solution Pvt Ltd


You can use whereMonth method, like this:

$cars = Car::whereMonth('created_at', '12')->get();

Example with determining if a month value is exist:

if ($request->has('month')) {
   $cars = Car::whereMonth('created_at', $request->input('month'))->get();
}
like image 8
Alex Avatar answered Nov 10 '22 06:11

Alex