i'm using Laravel as my PHP framework. its a convention to put index show store ...
functions in controllers.
i have 2 types of users(Admin & normal user). lets assume there is an Order
(in restaurant) model and i want to implement index
function for its controller.
a user can have more than one Order.
what i need is that this function:
- if admin is calling this API: returns all Orders
- if normal user is calling this API: returns just Orders owned by this user
i searched but i couldn't find anything(tbh i didn't know what to search).
once i did this as below which i didn't like because it looks two different functions gathered in one:
if ($user->role == admin) {
// fetch all orders
} else if ($user->role == normal_user) {
// just find user orders
}
so my question is what's best approach to achieve what i want?
The API supports 3 response types: JSON (Recommended) XML. NVP (Deprecated)
These operations stand for four possible actions, known as CRUD: Create, Read, Update and Delete. The server sends the data to the client in one of the following formats: HTML. JSON (which is the most common one thanks to its independence of computer languages and accessibility by humans and machines)
These methods – GET, POST, PUSH, PATCH, and DELETE – correspond to create, read, update, and delete resources. REST headers contain information that represent metadata associated with every single REST API request.
Such a REST API endpoint is typically a search allowing multiple filters, sorting and pagination. If so it is completly fine to apply different defaults for filters and also restrict filters to roles.
I would auto apply a filter user=currentUser for missing admin role and return a forbidden if a user without the admin role tries to apply a user filter for a different user.
With this approach you give admins also the functionality to search for offers of a specific user and you only need one search api to be used by the controller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With