Skip to content
Advertisement

Laravel accessor returning different month from the one in the database

I’ve got the following code. The first function works as expected when I output

{{ $event->date_and_time }} in my blade.

But, when try {{ $event->month }} I don’t get the correct month. No matter the month in the database, the output is always JULY. e.g this 2225-12-12T05:46 from the db outputs July instead of Dec. Can’t figure out what it is that I’m missing.

JavaScript

Advertisement

Answer

Your accessor has no value being passed to it since it is an accessor that isn’t for an attribute, it is virtual. So date_create isn’t getting a value to work with so it is returning the current date and time which is a date in July; hence it always says July as the month. You would need to get the attribute date_and_time and use that to pass to date_create and then get the Month from that.

JavaScript

On another note, use Carbon when you can as you can cast date and time fields to Carbon objects via Eloquent.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement