Home > Software design >  Laravel accessor returning different month from the one in the database
Laravel accessor returning different month from the one in the database

Time:07-28

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");
}

CodePudding user response:

Instead of passing parameter $date_and_time to accessor function, use $this->date_and_time. So in your code you have to edit to this:

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


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

Or even better you may use Carbon built-in library. So you can do only this:

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

protected $dates = ['date_and_time'];

And you can just access to it like $event->date_and_time->format('F d, h:ia') and if you want to get month then just $event->date_and_time->format('M')

CodePudding user response:

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.

  • Related