DEV Community

JohnDivam
JohnDivam

Posted on

Laravel routes: apiResource vs resource

Laravel routes application: using apiResource and resource. These methods help you create routes for a resource controller, following the RESTful conventions.

apiResource Function:

Route::apiResource('users', 'PostController');
GET           /users                      index   users.index
POST          /users                      store   users.store
GET           /users/{user}               show    users.show
PUT|PATCH     /users/{user}               update  users.update
DELETE        /users/{user}               destroy users.destroy

Enter fullscreen mode Exit fullscreen mode

resource Function

Route::resource('users', 'PostController');
GET           /users                      index   users.index
GET           /users/create               create  users.create
POST          /users                      store   users.store
GET           /users/{user}               show    users.show
GET           /users/{user}/edit          edit    users.edit
PUT|PATCH     /users/{user}               update  users.update
DELETE        /users/{user}               destroy users.destroy
Enter fullscreen mode Exit fullscreen mode

In summary

When using apiResource in Laravel, the routes are typically associated with the api middleware group by default. The api middleware group often excludes unnecessary middleware that is typically used for web requests, which can result in slightly faster performance compared to using the web middleware group.

The api middleware group usually includes middleware like throttle (for rate limiting) and auth:api (for API authentication). These are tailored for API routes, focusing on efficient handling of API requests.

On the other hand, the web middleware group includes middleware that are more suited for traditional web application routes, which might not be necessary or optimal for API routes.

So, if you're building an API and want to optimize for speed and efficiency, using apiResource with the api middleware group is a good choice. It ensures that the routes are handled with middleware optimized for API requests

Top comments (0)