DEV Community

JohnDivam
JohnDivam

Posted on

11 1 1 1

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay