Laravel 5 Carbon Format

- 1 answer

Edit: Thanks to Mr. Davidson's comment I changed my query to this:

$query->where(DB::raw('MONTH(date)'), '=', Carbon::parse($month)->format('m'));


In my expenses overview I have a dropdown where I can select a month which then queries only the results for that particular month, like so:

$query->where('date', 'LIKE', '%' . Carbon::parse($month)->format('m') . '%');

Before, my query was like this:

$query->where('date', 'LIKE', '%2015-' . Carbon::parse($month)->format('m') . '%');

In my database I have a datetime field, so the above works, but ofcourse it only shows results from 2015. I am trying to figure out how to use the first query to show results from 2016 also.



Instead of using whereRaw or LIKE, you can use the whereMonth method:

$query->whereMonth('date', '=', Carbon::parse($month)->format('m'));

Because it's much easier to read. The method is not documented in the Laravel Query Builder Docs, but you can check out the Query Builder API to see the method signature, as well as to check out what other methods are available for use when building queries (since there are quite a few that are not being described in the official documentation).