search

Home  >  Q&A  >  body text

What is the role of $hidden in laravel's Eloquent ORM?

$What is hidden used for? It would be best if you could give an example to explain

黄舟黄舟2757 days ago521

reply all(3)I'll reply

  • 巴扎黑

    巴扎黑2017-05-16 16:50:27

    The documentation is very clear. Hide attributes when converting to array or JSON

    Sometimes you may want to limit the attribute data that can appear in array or JSON format, such as password fields. Just add the hidden attribute to the model

    class User extends Model {
    
        protected $hidden = ['password'];
    
    }
    $user = user::find($userId);
    dump($user);//里面是木有password字段的

    reply
    0
  • 大家讲道理

    大家讲道理2017-05-16 16:50:27

    Sometimes you may wish to limit the attributes that are included in your model's array or JSON form, such as passwords. To do so, add a hidden property definition to your model

    class User extends Model {
    
        protected $hidden = ['password'];
    
    }

    reply
    0
  • PHPz

    PHPz2017-05-16 16:50:27

    You can hide any content after the Model query result toArray(). The basic usage has been explained above. Let me talk about the slightly more advanced usage that is usually used
    1 Hide a certain field.
    2 You can hide the relationship obtained by the query through the with method.
    3 It can also be used with $appends to change the return data format.
    For example, there is a User table and a UserInfo table. When querying, all fields of User + a certain field ClomnX in UserInfo are required. But I don’t want to return the entire UserInfo information. (Of course, it can be processed in a simpler way by making a query in the controller. I am just giving an example of unified processing using Model)

    class User extends Model {
    
        protected $hidden = ['userInfo'];
        
        protected $appedns = ['ClomnX']
        //声明一个关系,user和userInfo是一对一的关系
        public function userInfo()
        {
            return $this->hasOne(UserInfo::class);
        }
        
        public function getClomnXAttribute()
        {
            //判断使用了with方法关联了UserInfo。
            if (isset($this->getRelations()[UserInfo])) {
                return $this->UserInfo->ClomnX;
            } else return null;
        }
    class TestController
    {
        $user = user::with('userInfo')->find($userId);
        dump($user->toArray());//返回中没有UserInfo的数组信息,只有其中一个字段。
    }
    

    This is just a simple example, more complex format operations can also be implemented through this method. It's a good idea.

    reply
    0
  • Cancelreply