Reputation: 2579
The application I am migrating into Laravel 5 is a website and its API.
The API is used for the mobile apps and for the website to pull the data.
The website will not be developed to be a Single Page App, because I already have all the views and I'm just migrating the website to Laravel 5.
How can I do the following without duplicating my code?
For instance, allow /products
to list all my products using this API endpoint (/api/2.0/products
).
The same applies to all other routes
Upvotes: 5
Views: 3793
Reputation: 782
Yes you can. I am currently doing this myself. Writing the base API first and then dogfooding it for my own website. There is a good laravel package called Dingo ( https://github.com/dingo/api ) that can give different output depending on where you call it from. If you call it simply from api.yourwebsite.com/products you will get JSON. but if you call it internally like API::get('/products') you will get array/object whatever you're returning instead.
So I have a website that is using the API to render itself. This way, you only write the API once, and can use it for your frontend website, mobile, or give it to third party developers too.
I hope this answers your question. If you have any more questions, please let me know. Thanks
Upvotes: 5
Reputation: 653
You can do it by creating repositories for your code.
Then create separate controllers for both APIs and Website. Through that your code doesn't duplicated and you can access that repository from both the controllers and return response accordingly.
Upvotes: 1