K
K
kaxa32012022-03-25 17:02:45
Laravel
kaxa3201, 2022-03-25 17:02:45

How to hide api fields based on user permission?

Suggest best practices.
There is a rest api by which you can get products with fields ['name' =>'test', 'price'=>22], depending on the user's permissions, you need to hide the fields, let's say the user who requests the list of products does not have the permission 'products.price' .view' and then you need to hide the 'price' field in the response.

I know that you can hide fields in Resource and check each field for user permissions, but I can’t figure out how to store the mapping of fields with permissions.
Please tell me how best to do it, maybe I’m looking in the wrong direction at all and can I make it easier and more versatile?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gerasimov, 2022-03-26
@kaxa3201

Use API-Resources
You will have a request in the resource - from which you can get the desired user.
Then, in the toArray() method, through the when function, set the required fields, for example:

'secret' => $this->when($request->user()->isAdmin(), function () {
    return 'secret-value';
}),

To check permissions, you can use $request->user()->can(...)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question