Routing
Effective route structuring is fundamental to a well-designed RESTful API. Always make sure your routes are adhering to the REST principles. Best practices are to stick to the Laravel structure, where this will also work perfectly with the resources 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} | delete | 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.
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.
PHP
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PhotoController;
Route::apiResource('photos', PhotoController::class);
PHP
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
Route::apiResource('users', UserController::class);
You can read more on the laravel docs https://laravel.com/docs/12.x/controllers#resource-controllers
Table of Contents
