Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a Website and API REST with Laravel with the same Controllers?

I'm really new in Laravel Framework, I want to develop a Web Application that also has their own API Rest, but I don't know which is the best way to do it.

I want that the Controllers and methodos could be the sames for a Web opperation and for a API REST operation, for example for the Module of Users if I make a request like this:

http://myproject.com/userRegister/

Then the web shows me a view HTML with a form for user registration, but if I call a request like this:

http://myproject.com/api/userRegister/

Then the response will be a JSON with the Form data that I need for register the user.

I want that both of them use the UserRegisterController and the same method for example : "formRegister", all of this for avoid repeat bussines logic in differents methods.

Any idea of what is the best way to do this? I researched and some people recommend make all the services with JSON responses and parse with AngularJS or similar, but I don't want that, I want only use Laravel with HTML.

like image 835
Roberto Briones Argüelles Avatar asked Sep 02 '15 03:09

Roberto Briones Argüelles


1 Answers

Let the same controllers handle api and web requests is not the best decision. Sooner or later this logic will lead to the mess in your code.

Do not forget to keep your controllers as thin as possible and move most of your logic to models, services and repositories. This will help you to have two standalone controllers versions that will have as less code as possible.

But if you still want to combine them you can use \Request::acceptsJson() \Request::acceptsHtml() methods to determine what type of request you have.

like image 145
Maxim Lanin Avatar answered Oct 22 '22 10:10

Maxim Lanin