Laravel attribute casting 导致的 Indirect modification of overloaded property


在 Laravel model 中,设置了某个属性做 array casting.

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

但是在 controller 中执行

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

时,报错

production.ERROR: Indirect modification of overloaded property

可见,casting 并不支持一些针对特定类型的操作,例如无法作为指定类型的函数的参数。

按照官方文档的做法,应该是先赋值给一个中间变量,进行操作,然后再赋值回去。

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

所以正确的做法应该是

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

collection casting

发现还有 collection casting 的支持,于是尝试了一下。

// casting 类型 - 'rounds' => 'array' + 'rounds' => 'collection' // collection 的 push 操作 // 需要注意,push 之后,需要重新赋值回去。 - array_push($record->rounds, date("Y-m-d H:i:s")); + $record->rounds = $record->rounds->push(date("Y-m-d H:i:s")); // 初始化 - $game_record->rounds = []; + $game_record->rounds = collect([]); 

casting 支持的类型

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM