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.
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