Api
Routing
Routing structure and best practices
Effective route structuring is fundamental to a well-designed RESTful API. Always make sure your routes are adhering to the REST principles. Best practice is to stick to the Laravel structure, which also works perfectly with resource controllers.
REST Routes
| Verb | URI | Action | Route Name |
|---|---|---|---|
| GET | /photos | index | photos.index |
| GET | /photos/create | create | photos.create |
| POST | /photos | store | photos.store |
| GET | /photos/{photo} | show | photos.show |
| GET | /photos/{photo}/edit | edit | photos.edit |
| PUT/PATCH | /photos/{photo} | update | photos.update |
| DELETE | /photos/{photo} | destroy | photos.destroy |
Resource Controller
Use API resource routes: Laravel's Route::apiResource method simplifies the creation of resourceful API routes. It automatically generates routes for standard CRUD operations like index, store, show, update, and destroy.
routes/photos.php
use App\Http\Controllers\PhotoController;
Route::apiResource('photos', PhotoController::class);
Organize Routes
For larger applications, consider separating routes into multiple files to keep them organized & maintainable.
routes/photos.php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PhotoController;
Route::apiResource('photos', PhotoController::class);
You can read more in the Laravel docs:
