Tag Archives: Indirect modification of overloaded property

[Solved] Laravel attribute casting Error: Indirect modification of overloaded property

In the laravel model, set an attribute to do array casting

protected $casts = [
        'rounds' => 'array',
];

But it is executed in the controller

array_push($record->rounds, date("Y-m-d H:i:s"));

Report an error

production.ERROR: Indirect modification of overloaded property

It can be seen that casting does not support certain types of operations, for example, it cannot be used as a parameter of a function of a specified type

According to the official document, you should first assign a value to an intermediate variable, operate it, and then assign it back

$user = App\User::find(1);
$options = $user->options;
$options['key'] = 'value';
$user->options = $options;
$user->save();

So the right thing to do is

$tmp = $record->rounds;
array_push($tmp, date("Y-m-d H:i:s"));
$record->rounds = $tmp;
$record->save();

collection casting

I found that there was also support for collection casting, so I gave it a try

// casting type
-  'rounds' => 'array'
+  'rounds' => 'collection'

// The push operation of the collection
// Note that after pushing, you need to reassign the value back.
-  array_push($record->rounds, date("Y-m-d H:i:s"));
+ $record->rounds = $record->rounds->push(date("Y-m-d H:i:s"));

// Initialization
-  $game_record->rounds = [];
+ $game_record->rounds = collect([]);

Types of casting support

integer, real, float, double, string, boolean, object, array, collection, date, datetime, and timestamp.