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