How to hide relationship columns in laravel?

前端 未结 4 558
花落未央
花落未央 2021-01-18 01:48

I have a statement like this:

App\\User::with(\'client\')->find(2)->makeHidden(\'client.phone_no\');

I want to hide certain columns f

相关标签:
4条回答
  • 2021-01-18 01:59

    With accepts a callback to modify the query.

    $users = User::with(['client' => function($query) {
            $query->select(['id', 'name']);
        }])->find(2);
    

    You could also define default hidden attributes on your Client model

    protected $hidden = ['phone_no'];
    
    0 讨论(0)
  • 2021-01-18 02:05

    If you don't want to hide the phone_no for all the requests by adding it to the hidden property, you could do something like this:

    $user = App\User::with('client')->find(2);
    $user->client->makeHidden('phone_no');
    return $user;
    

    As I stated in my comment to the original question: I found this method as well. I believe this should be the method you should use when you want to exclude columns more often. If you only want to exclude a column once, my solution should be sufficient.

    0 讨论(0)
  • 2021-01-18 02:08

    You can either hide the column in the query result (eager loading is unnecessary):

    $user = User::find(2);
    $user->client->makeHidden('phone_no');
    

    Or you don't even get it from the database:

    $user = User::with('client:id,user_id,...' /* other columns except phone_no */)->find(2);
    
    0 讨论(0)
  • 2021-01-18 02:18

    You can create a scope in your model and apply it in builder

    Define these functions in your model

    protected function columns(){
        return Schema::getColumnListing('clients');
    }
    
    public function scopeExclude($query, $value = array()) 
    {
      return $query->select( array_diff( $this->columns(), $value) );
    }
    

    Now use it in query builder

    App\User::with(['client' => function($query){
        $query->exclude(['phone_no']);
    }])->find(2)
    
    0 讨论(0)
提交回复
热议问题