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.

protected $fillable = [
    'title',
    'description',
    'date_and_time',
    'location',
    'price',
    'activity_status',
    'contact',
    'slug',
    'user_id',
];

public function getDateAndTimeAttribute($date_and_time)
{
    $date_and_time = date_create($date_and_time);
    return date_format($date_and_time, "F d, h:ia");
}

public function getMonthAttribute($date_and_time)
{
    $date_and_time = date_create($date_and_time);
    return date_format($date_and_time, "M");
}

>Solution :

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.

public function getMonthAttribute()
{
    // to get the DateTime from the original string
    $date_and_time = date_create($this->getRawOriginal('date_and_time'));
    // or to get the DateTime object from the formatted date from the `date_and_time` accessor
    $date_and_time = date_create($this->date_and_time);

    return date_format($date_and_time, "M");
}

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

Leave a Reply