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.

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式