Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 website and API using the same app

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

like image 902
Jad Joubran Avatar asked Mar 10 '15 10:03

Jad Joubran


People also ask

Can we use API in Web php in Laravel?

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.

Can I use Laravel for API only?

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.

What is Laravel REST API?

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.


2 Answers

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

like image 58
Sameer Nyaupane Avatar answered Sep 30 '22 20:09

Sameer Nyaupane


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.

like image 35
Raviraj Chauhan Avatar answered Sep 30 '22 22:09

Raviraj Chauhan