I’m looking to structure my Laravel application to efficiently handle both API and view functionalities while avoiding duplication in controllers.
How can I set up my application to have two separate controllers, one dedicated to API actions and the other to view-related actions?
Additionally, what’s the best way to handle shared logic between these controllers, and how can I ensure proper separation of concerns?
2
Answers
You can make same class name that can be used both for API and views. By making controller in different namespaces, e.g.
For shared concerns, create Traits folder in app, then create PHP trait class.
You can use it either in your model or controller with use.
For isolated concerns and structured development, you can create service or repository patterns.
For more information, follow.
To achieve this, you have to move your logic of your controllers to a separated class/repository than you can call it from your controllers api/web (web is the controllers which you use views), to have a clean structure in your controllers create two folders api and web to separate your controllers (although you can create one controller and not two, i’ll explain this at the end).
Example
let’s take an example where you need to show the lists of posts to your user:
AppRepositoriesPostsRepository.php :
now in your controllers (web,api) :
AppHttpControllersWebPostController.php :
and in the api controller :
AppHttpControllersApiPostController.php :
this way, you can separate the data delivery to user (api or web) but still have one source of data ($postsRepository->getUserPosts()) so you avoided duplication.
Even though, you can use one controller for both Api and Web :
you can the
wantsJson
methods for example :AppHttpControllersPostController.php :
And for the
api
clients add this header to their requets: