I created a mutator in model class as follows:
public function setFileDataAttribute($value)
{
if (is_null($value)) {
$value = [];
}
return $value;
}
The corresponding field is : file_data. Catsts and fillables are also set:
protected $casts = [
"created_at" => "datetime:Y-m-d H:i",
"file_data" => "array",
];
protected $attributes = [
"file_data" => [],
];
I have really tried everything, but it is simply not called (I have dd-ed it - nothing) Anyone, any idea?
Update: The class is (simplified):
class XXX extends Model
{
use HasFactory;
use SoftDeletes;
protected $fillable = [
"name",
"cost_type",
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
"file_data" => "array",
];
protected $attributes = [
"file_data" => [],
];
public function setFileDataAttribute($value)
{
if (is_null($value)) {
$value = [];
}
return $value;
}
}
I think you are missing something here; You need to actually set the value, using
$thiskeyword. For example:Or better:
There are differences between accessor and mutators. If you want to use accessor, you can use
getkeyword instead ofsetand your approach is just fine, however, if you want to mutate it when you are inserting or updating the database, you need to assign it to the attribute.Accessor: An accessor transforms an Eloquent attribute value when it is accessed.
Mutator: A mutator transforms an Eloquent attribute value when it is set.
More at: https://laravel.com/docs/8.x/eloquent-mutators#defining-a-mutator
I hope it helps.