What is the best practice for designing a single application that contains an API that will be used by mobile devices, and also has a web application?
Do I design single controllers with logic that checks if user wants JSON? or dedicated controllers for web and api - if yes, how to I prevent duplication of logic. I assume there will be similarities - they will typically handle data in the same way, but one will return json, while other redirects or sends data to to given view. Can the common code be moved to a separate layer eg services?
Any help including open source code will be appreciated.
I would split them both up! So everything related to your web application can be found in the following files
routes/web.php
app/Http/Controllers
Everything related to your api should be available in
routes/api.php
app/Http/Controllers/Api
Note that the routes setup come by default in Laravel. You can easily create your own routes with a different namespace in the RouteServiceProvider to keep them separated.
It's best practice to create service classes and/or repositories that can be reused in both controllers.
Let me know if you have more questions or need more examples ;)