1

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

  • uid
  • username
  • password
  • dob
  • usergroup
  • avatar

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.

rossanmol
  • 1,633
  • 3
  • 17
  • 34
  • I wouldn't recommend trying to dynamically set `$hidden`, you should try using scopes. – Devon Bessemer Jan 07 '17 at 23:29
  • Possible duplicate of [How to exclude certains columns while using eloquent](http://stackoverflow.com/questions/23612221/how-to-exclude-certains-columns-while-using-eloquent) – Devon Bessemer Jan 07 '17 at 23:30
  • You're overthinking it. If the data you want to return varies depending on the request, then you modify it in each corresponding controller action. Not in the model itself. – maiorano84 Jan 07 '17 at 23:32

1 Answers1

1

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!

Rwd
  • 34,180
  • 6
  • 64
  • 78