RESTful Resource Controllers of Laravel

Resource Controllers are built RESTful controllers around the resource. For example, if we have one resource called ‘Profile’. Now this RESTful controller handles HTTP request for ‘Profile’ resource.

using the make: controller command we can create a controller for profile

php artisan make:controller ProfileController

Now, this controller contains all the methods like GET, POST, PUT as per the requirement of function.

Resource full route for the controller

Route::resource('profile', 'ProfileController');

This single route declaration creates multiple routes to handle a variety of RESTful actions on the profile resource.

Types of Resource Routes: Partial, Naming, Nested….

  1. Partial Resource Routes: When declaring a resource route, you may specify a subset of actions to handle on the route:
Route::resource('profile', 'ProfileController',
['only' => ['index', 'show']]);

Route::resource('profile', 'ProfileController',
['except' => ['create', 'store', 'update', 'destroy']]);

2. Naming Resource Routes:

Route::resource('profile', 'ProfileController',
['names' => ['create' => 'profile.build']]);

3. Nested Resource Routes:

Sometimes you may need to define routes to a “nested” resource. For example, a profile resource may have multiple “posts” that attached to the photo and maybe caption or description. To “nest” resource controllers, use “dot” notation in your route declaration:

profile/{profile_id}/posts/{post_id}