Streamlining API Routes in Laravel: The apiResource Method

Streamlining API Routes in Laravel: The apiResource Method

Ever found yourself manually excluding HTML template routes when building an API? Laravel's apiResource method is here to make your life easier! Let's dive into how this feature can streamline your API route definitions.

The apiResource Basics

Instead of using the standard resource method and excluding routes, you can use apiResource:

use App\Http\Controllers\PhotoController;

Route::apiResource('photos', PhotoController::class);

This automatically excludes the create and edit routes that are typically used for HTML forms.

Working with Multiple API Resources

Need to register multiple API resources? The apiResources method has got you covered:

use App\Http\Controllers\PhotoController;
use App\Http\Controllers\PostController;

Route::apiResources([
    'photos' => PhotoController::class,
    'posts' => PostController::class,
]);

Quick Controller Generation

Laravel also provides a convenient way to generate API-specific controllers:

php artisan make:controller PhotoController --api

This command creates a controller without the create and edit methods, perfect for API resources.

Real-World Example

Here's how you might set up an API for a social media platform:

use App\Http\Controllers\Api\PostController;
use App\Http\Controllers\Api\CommentController;
use App\Http\Controllers\Api\UserController;

class ApiRouteProvider extends ServiceProvider
{
    public function boot()
    {
        Route::prefix('api/v1')->group(function () {
            Route::apiResources([
                'posts' => PostController::class,
                'comments' => CommentController::class,
                'users' => UserController::class
            ]);
        });
    }
}

This sets up the following routes for each resource:

  • GET /api/v1/posts (index)
  • POST /api/v1/posts (store)
  • GET /api/v1/posts/{post} (show)
  • PUT/PATCH /api/v1/posts/{post} (update)
  • DELETE /api/v1/posts/{post} (destroy)

The apiResource method helps you build clean, RESTful APIs while following Laravel's conventions. It's a small feature that can save you time and keep your routes organized.

If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter. It helps a lot!

Subscribe to Harris Raftopoulos

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe