rossanmol
rossanmol

Reputation: 1653

Dynamic $visible, $hidden for a Laravel Model

Let's say I have User model with the following attributes:

When providing JSON I should hide the password, so I will write:

$protected $hidden = ['password'];

When a request is being made for user data, I would like the model to respond with only: uid, avatar, dob.

When a request is being made for security data, I would like the model to respond with only: uid, username, usergroup.

How can I set predefined groups of $visible and $hidden attributes for different request inside model configuration, without using controllers which will make my code messy.

Upvotes: 1

Views: 4504

Answers (1)

Rwd
Rwd

Reputation: 35180

As @maiorano84 mentioned in the comments you wouldn't add multiple $hidden/$visible properties for this. These properties are more for general purpose so you don't have to worry about removing certain attributes each time you just want to return an instance in a request.

If you're only wanting to return specific fields in certain requests then you would be more explicit about it.

In one of your examples above you mentioned only returning uid, username and usergroup which you could do with the something like:

return collect($user)->only('uid', 'username', 'usergroup');

Hope this helps!

Upvotes: 1

Related Questions