Laravel - Model filter date field by month

12,192

Solution 1

You should try this:

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

Solution 2

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();
}
Share:
12,192
edica
Author by

edica

Updated on June 18, 2022

Comments

  • edica
    edica almost 2 years

    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();
    
  • AddWeb Solution Pvt Ltd
    AddWeb Solution Pvt Ltd about 6 years
    @edica: Thanks for upvote. Feel free to accept this as answer if our solution addressed your concern. Thanks
  • Osify
    Osify about 5 years
    This answer is more practical base on the API and answer to the question even: filter by Month, Year or Day. Thanks