I'm making a course on Laravel Sanctum: MasteringAuth.com

Avoid this PHP Carbon mistake

Constantin Druc ยท 31 Jul, 2021

[00:02] But if I select June, press filter, well... it returns files from July, so what the hell happened???

[00:10] So I was recording the next episode in the "building a media library series" and I've noticed something really strange with the date filter. If I select May, press filter, it works, I see files from may. If I select July, press filter, I see files from July.

[00:22] But if I select June, press filter, well it returns files from... July. So what the hell happened? Let me show you the piece of code in question. Here it is: I'm creating two carbon objects using the createFromFormat method. The month that gets passed in also specifies the year so we do createFromFormat, month, year, we pass in the parameter, and then we get the start and the end of the month. So pause the video, think about what may be wrong, and write a comment - I'm really curious to see how many of you know about this issue.

[01:11] Okay, so here's what's wrong. Apparently when you create a date from a format where you only specify the month and the year but not the day, the current day of the month is used, and today is 31st of july, meaning that carbon will use 31 when creating the date object. But there is no 31st of June this year, so carbon will pick up the next day, which is 1st of July; leading us to create the wrong date object.

[01:42] So the lesson is, if you ever need to do something like this where you grab the start and the end of the month, make sure you also specify the day. So let's fix this by adding the day in the format and renaming the parameter to make it more specific. Now to make sure we are sending the full date we can go to our MediaController where these dates are queried, and change the format to include the first day of the month. So we'll do 01 dash and save.

[02:08] Now if I go back into browser, refresh, select may it sends 1st of May, 1st of June, and now we are getting the correct files. Remember to always specify the day, month, and year when creating dates, otherwise you'll end up being unpleasantly surprised like I did.