John Doe
John Doe

Reputation: 876

Laravel Model Fields Returned Based on Whether User Logged In

I have a model called Channel, which some are publicly or privately available depending on whether you have purchased it.

I was wondering what would be the best way to restrict access to some of the fields if you have not logged in or purchased the channel.

This is being used on an RestFUL API and I am using JWT therefore at any given time can check the header to see if it is present.

I was thinking maybe overriding Laravel's toArray function on the model and unset certain fields if the requirements are not met, but not sure if this is best practice!

Any ideas?

Upvotes: 0

Views: 60

Answers (1)

Dan Matthews
Dan Matthews

Reputation: 1245

If you're looking to do the minimal amount of work here then yes - overriding toArray() and probably even toJson() would work, but to me it feels 'janky'.

The $hidden array controls which fields will be returned when a model is rendered as JSON, so you could create a chainable method that alters the $hidden array before returning the response:

$model = \App\MyModel::find($id);
return $model->adaptFieldsToAuthStatus();

You would do this by having a bunch of conditionals in the adaptFieldsToAuthStatus() function that add fields to the $hidden array:

if (Auth::check()) {

  $this->hidden[] = 'super_secret_field_name';
  $this->hidden[] = 'super_secret_field_name2';

}

// Return the instance of the class so it's chainable.
return $this;

I think that's how i would do it.

Upvotes: 0

Related Questions