Laravel Eloquent Serialization: how to rename property?

前端 未结 2 1186
佛祖请我去吃肉
佛祖请我去吃肉 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;
    }
    
    0 讨论(0)
  • 2021-01-02 03:37

    Add single "aliases" using attribute accessors

    You can use attribute accessors to create "new attributes":

    public function getUserIdAttribute(){
        return $this->attributes['user_id'];
    }
    

    This allows you to access the value this way: $user->userId

    Now let's add the value to array / JSON conversion:

    protected $appends = array('userId');
    

    And finally hide the ugly user_id:

    protected $hidden = array('user_id');
    


    Convert all attribute names when converting to array / JSON

    You can also use toArray() to change the all attribute names when converting the model into an array or JSON string.

    public function toArray(){
        $array = parent::toArray();
        $camelArray = array();
        foreach($array as $name => $value){
            $camelArray[camel_case($name)] = $value;
        }
        return $camelArray;
    }
    
    0 讨论(0)
提交回复
热议问题