1

In my User model, I have an appends fields:

protected $appends = [
      'is_admin'
];

It will appends is_admin field in every request by using with() eager loading. However, in some scenario I don't want to return is_admin field, I am trying to use the follows:

$this->belongsTo('App\Models\User')
            ->select(['id', 'username', 'first_name', 'last_name']);

But it doesn't work. Is the appends field always be appended even I use custome select field ?

2 Answers 2

2

appends is used when the model is serialized; it 'appends' attributes to the output.

If you have a single model and you want to not have the appends accessors added to the serialized data, you can set them hidden.

Example:

$test = new class extends Illuminate\Database\Eloquent\Model {
    protected $appends = ['is_admin'];

    public function getIsAdminAttribute() {
        return rand(0, 1);
    }
};

dump($test->toArray()); // will contain 'is_admin'

$test->makeHidden('is_admin');

dump($test->toArray()); // will not contain 'is_admin'

// This can be applied to Eloquent Collections.

$model->relation->makeHidden('is_admin');

One way of doing it.

Sign up to request clarification or add additional context in comments.

2 Comments

I try to add $this->belongsTo('App\Models\User')->makeHidden('is_admin') but it will output error: Call to undefined method Illuminate\Database\Query\Builder::makeHidden()
Its not a builder method, its a model method. Call it on an instance of a model or a collection of models.
0

Simply put this result to a variable

$data = $this->belongsTo('App\Models\User')->select(['id', 'username', 'first_name', 'last_name']);  

and use directly

$data->makeHidden("is_admin");

This will work for you

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.