Hello everyone! Today, we want to talk about one of the interesting features of Laravel 11 that gives you the ability to create advanced controllers using the method ResourceRegistrar::prefixedResource()
. This feature becomes particularly beneficial when you want to create a specific route with a specified prefix, which is quite common.
For example, suppose you have an e-commerce website and you want to create a RESTful API. Using the prefixedResource
method allows you to create a collection of routes for specific URL resources with a designated prefix. This approach can help improve your source code organization and, while preserving standards, makes your code more readable.
Before anything else, make sure that the necessary controllers and models are in place for creating these routes. After that, by using this method, you can define the routes. Laravel can automatically create CRUD routes for you, so you won’t need to manually write them every time.
Now, let’s take a look at how to use prefixedResource
. We will use a small project that manages a resource called products
.
Route::prefix('api')->group(function () {
Route::resource('products', ProductController::class);
});
Code Explanations
Here, we have created a group of routes that begins with api
:
Route::prefix('api')->group(function () { ... });
Then, by using Route::resource('products', ProductController::class);
, we define the routes associated with the product controller:
Route::resource('products', ProductController::class);
This code automatically generates the GET
, POST
, PUT
, and DELETE
routes for your products.