AydenWH's avatar

Laravel - Purpose and different between web.php and api.php

I know this question might sound stupid but I really want to know the purpose and when should I use web.php and api.php.

If I create a web application only serve for web purpose, I should focus all my route on web.php?

And if I create a web application which serve for mobile application to retrieve data, I should defined all my routes on api.php?

That is to say every route should be defined in web.php if it is not related with web service.

Please correct me if I am wrong.

0 likes
5 replies
Erulezz's avatar

Yes, for all your requests for normal web applications, use web.php. If you have a mobile app (iOS, Android for example) define your routes in api.php, so use both files.

I have my CMS routes all defined in web.php, and for the mobile apps I define my route calls in api.php.

3 likes
AydenWH's avatar

@Erulezz

If I am using axios for ajax request.

I must use api.php in order to fetch data?

samfrjn11's avatar
Level 3

@tyris No, you can perfectly define your routes for your ajax request in web.php

But using api.php has some advantages:

  • routes are automatically prefixed with 'api/'
  • routes are using auth and api middle ware -- auth -> checks for a token -- api middleware adds some additional security/protection by throttling api request. So a client can request a route only x time per minute

I use api.php for ALL my ajax routes.

16 likes
Jaytee's avatar

The api file can do exactly what the web file can do. You can see this in the RouteServiceProvider.

The only difference is: the prefix and middleware.

12 likes

Please or to participate in this conversation.