What Is Scoping Resource Routes In Laravel With Example

admin_img Posted By Bajarangi soft , Posted On 17-09-2020

Laravel resource controllers provide the CRUD routes to the controller in a single line of code. A resource controller is used to create a controller that handles all the http requests stored by your application. The resource() is a static function like get() method that gives access to multiple routes that we can use in a controller.

What Is Scoping Resource Routes In Laravel With Example

Scoping Resource Routes

To know more about creating resource controller visit our Bajarangisoft site.

Sometimes, when implicitly binding multiple Eloquent models in resource route definitions, you may wish to scope the second Eloquent model such that it must be a child of the first Eloquent model. For example, consider this situation that retrieves a blog post by slug for a specific user:

 

use App\Http\Controllers\PostsController;

Route::resource('users.posts', PostsController::class)->scoped();


You may override the default model route keys by passing an array to the scoped method:
 
use App\Http\Controllers\PostsController;

Route::resource('users.posts', PostsController::class)->scoped([
'post' => 'slug',
]);

When using a custom keyed implicit binding as a nested route parameter, Laravel will automatically scope the query to retrieve the nested model by its parent using conventions to guess the relationship name on the parent. In this case, it will be assumed that the User model has a relationship named posts (the plural of the route parameter name) which can be used to retrieve the Post model.
 

Related Post