Return model attributes based on OAuth token scope

Viewed 115

How could I return a laravel model based on the scopes from the access token the request is using for authorization similar to how discord does it with its identity and email scopes here. I'd like to basically 'dynamically' hide/show specific attributes in a model based on the token scope

Would this be something that would be defined in a controller or in the model?

1 Answers

Decided to make use of the Laravel API Resources and the conditional attributes

class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'username' => $this->username,
            'email' => $this->when($request->user()->tokenCan('email'), $this->email),
        ];
    }
}
Related