Laravel API Best Practice

- 1 answer

Ad

I'm building API with laravel 5.1.

I have 3 section access: User, Admin, Super Admin.

I'm curious about the practice for handling the controller. Right now I make 3 different controller for each section. But sometimes I need to call same function inside the controller. Such as Product:all().

Should I really make 3 different controller or i can use only 2 controller for the best practice?.

Ad

Answer

Ad

I would just use one controller/one route /api/v1/products when the returned dataset is the same for all users (i.e. for basic users, admins and super admins).

I guess that each admin/super admin is also a user. So you should protect your /api/v1/products route with a middleware that just checks if the user is an authenticated user, because then he is allowed to access the data.

If there is some data other than products that can only be accessed by an admin/super admin, you should create another middleware for that. It is never necessary to create two or more controllers/routes for the exact same API.

Ad
source: stackoverflow.com
Ad