Laravel Eloquent Serialization: how to rename property?

前端 未结 2 1222
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-02 03:12

For example, I have User model extending Eloquent. In the database table, the column name is user_id.

How do I output the result as \'userId\' after re

2条回答
  •  感动是毒
    2021-01-02 03:29

    I do it in this way.

    protected $remap_attrs = ['old_name' => 'new_name'];
    public function toArray(){
        $array = parent::toArray();
        foreach($this->remap_attrs as $key => $new_key) {
            if(array_key_exists($key, $array)) {
                $array[$new_key] = $array[$key];
                unset($array[$key]);
            }
        }
        return $array;
    }
    

提交回复
热议问题