I am working on building API and so far I’ve familiar with the web route.I was wondering can we share the same controller for both web and API.
I already have a controller file which is working for web route right now
LIke this url for the web route :
Route::post('product', [GuestuserController::class, 'product']);
Now i want to use same controller for API too because i don`t want to update the code for API again again if anything change in web code , i want the changes make in web automatically reflect the API too.
Could anyone suggest me a solution for this so i can move further.
2
Answers
Although it’s possible to define the same controller in api.php and web.php, it’s not a good practice.
You should rather, create a service class and move your business logic there.
This way, you can call the service from any controller, API, or web
Example
Then in API controller or Web controller
It depends. But a clear demarcation would be advantageous. You never know. Example what you could do:
web.php uses :
class AController extends ParentController {}
api.php uses:
class Api/AController extends ParentController {}
In the ParentController you add your common methods that use the web as well as the api route. This way you would be more flexible than with your variant and you don’t have any redudant code.