Laravel - Controllers - Resource Controllers
If you think of each Eloquent model in your application as a "resource", it is typical to perform the same sets of actions against each resource in your application. For example, imagine your application contains a
Photo model and a
Movie model. It is likely that users can create, read, update, or delete these resources.
Because of this common use case, Laravel resource routing assigns the typical create, read, update, and delete ("CRUD") routes to a controller with a single line of code. To get started, we can use the
make:controller Artisan command's
--resource option to quickly create a controller to handle these actions:
php artisan make:controller PhotoController --resource
This command will generate a controller at
app/Http/Controllers/PhotoController.php. The controller will contain a method for each of the available resource operations. Next, you may register a resource route that points to the controller:
use App\Http\Controllers\PhotoController; Route::resource('photos', PhotoController::class);
This single route declaration creates multiple routes to handle a variety of actions on the resource. The generated controller will already have methods stubbed for each of these actions. Remember, you can always get a quick overview of your application's routes by running the
route:list Artisan command.
You may even register many resource controllers at once by passing an array to the
Route::resources([ 'photos' => PhotoController::class, 'posts' => PostController::class, ]);