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:
- Set the field as non-null when creating the migration.
- short the field name with a single underscore (start_time)
- Do it through "$cast" instead of doing it with an accessor
- put it in "$append"
But none of those methods work.
Any ideas please?
$appends
property is used to append new, computed attributes to a model's array / JSON form, not for existing columns. Sincestart_working_time
is an actual column in your database, you shouldn't list it in$appends
. Removestart_working_time
from the$appends
array.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: