Laravel accessor not working on time field

55 Views Asked by At

I am trying to set a field when getting it from the database, and the corresponding accessor does not work. It simply does not execute.

My code is as follows:

Migration:

public function up(){
    Schema::table('users',function(Blueprint $table){
        $table->time('start_working_time')->nullable();
    });
}

Model:

protected $fillable = [...,'start_working_time'];

protected $casts = [
    'start_working_time' => 'datetime:H:i',
];

protected $appends = ['start_working_time'];


public function getStartWorkingTimeAttribute($date){
    return Carbon::createFromFormat('H:i:s',$date)->format('H:i');
}

What I've tried:

  1. Set the field as non-null when creating the migration.
  2. short the field name with a single underscore (start_time)
  3. Do it through "$cast" instead of doing it with an accessor
  4. put it in "$append"

But none of those methods work.

Any ideas please?

1

There are 1 best solutions below

0
On
  1. The $appends property is used to append new, computed attributes to a model's array / JSON form, not for existing columns. Since start_working_time is an actual column in your database, you shouldn't list it in $appends. Remove start_working_time from the $appends array.
  2. If you're casting start_working_time as a datetime, Laravel is already returning this as a Carbon instance. Therefore, in your accessor, you don't need to create another Carbon instance. You can simply format it:
public function getStartWorkingTimeAttribute($date){
    return $date->format('H:i');
}