Grouping routes by controllers in Laravel 8.x
There are many ways using which you can group your routes in Laravel right now. For instance, as by middlewares, subdomains, prefixes to name a few.
But there’s one more scenario, that can be covered, that was missing.
Consider the following group of routes.
use Illuminate\Support\Facades\Route;
Route::get('/', [BookController::class, 'index']);
Route::get('/books/{id}', [BookController::class, 'show']);
Route::get('/books/search/{search}', [BookController::class, 'search']);
Route::post('/book', [BookController::class, 'store']);
As you can tell, we have four routes to manage books and if you notice, all of these routes have one thing in common. i.e. the BookController
.
What if we could just group these routes by the controller? The routes would become more manageable and concise. No?
Well, a recent PR for Laravel 8.x attempts to solve this.
Group by Controller
According to this PR, the framework now comes with a controller
method (that you can call on the Illuminate\Support\Facades\Route
facade) using which you can group the routes which are using the same controller.
So, if we want to rewrite the previous example using this approach, here’s how we can do it.
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BookController;
Route::controller(BookController::class)->group(function () {
Route::get('/', 'index');
Route::get('/books/{id}', 'show');
Route::get('/books/search/{search}', 'search');
Route::post('/book', 'store');
});
As you can tell, by using this approach now you have all the routes, that use the same controller, are under the same group. Now, you only need to provide the controller method that they are invoking.
Falling back
Now, if you’re grouping routes by controllers using the above approach and if you specify the controller on the route once again, it will override the group controller.
Consider the following for example.
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BookController;
Route::controller(BookController::class)->group(function () {
Route::get('/books/{id}', 'EbookController@show');
});
As you can tell, we specified the EbookController
on the route definition once again. So, this will take the priority over the BookController
in this case.
It’s the same for other syntaxes of specifying controllers as well such as an array, closure syntax, and invokable controllers.
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.