Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading