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
In a Laravel application, you will define your “web” routes in routes/web. php and your “API” routes in routes/api. php. Web routes are those that will be visited by your end users; API routes are those for your API, if you have one.
Laravel provides a flexible API authentication system that you can build on. There are Laravel packages like Passport and Sactum which you can use as drivers for authenticating API requests. There's a route file that controls API routes and works just as simplistic as the web routes.
Laravel | August 25, 2021 | A RESTful API is an application programming interface that adjusts to REST engineering style's limitations and considers cooperation with RESTful web services.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With