DEV Community

Sanz
Sanz

Posted on

How to Improve Routing In Laravel

Routing allows the user to route application requests to its appropriate controller. Laravel has inbuilt API which is really helpful and time saving. Hence, it is important for newcomers to know and extend their knowledge about routing.

Users can learn about routing technique basics from here. Please go through the link to get more familiar with routing.

Here are a few tricks that can help you to use routing in Laravel:
Using Custom Namespace

Users can define namespace for a group of routes using fluent routing API.

Route::namespace('Admin')->group(function () {
    // Controllers Within The "App\Http\Controllers\Admin" Namespace
});
Enter fullscreen mode Exit fullscreen mode

Run the command given below to create controller in App\Http\Controllers\Admin:

php artisan make:controller -r Admin/UsersController
Enter fullscreen mode Exit fullscreen mode

After running the command, routes/web.php will look like this:

Route::namespace('Admin')
    ->prefix('admin')
    ->group(function () {
        Route::resource('users', 'UsersController');
    });
Enter fullscreen mode Exit fullscreen mode

Debug Routes

To find or debug all defined routes, users can run php artisan route:list . Basically what this command does is that it helps to see name of all routes and attached middleware to the route.

php artisan route:list
+--------+----------+----------+------+---------+--------------+
| Domain | Method   | URI      | Name | Action  | Middleware   |
+--------+----------+----------+------+---------+--------------+
|        | GET|HEAD | /        |      | Closure | web          |
|        | GET|HEAD | api/user |      | Closure | api,auth:api |
+--------+----------+----------+------+---------+--------------+
Enter fullscreen mode Exit fullscreen mode

If you are interested, you can continue this post on https://laravelproject.com/how-to-improve-routing-in-laravel/.

Top comments (2)

Collapse
 
bdelespierre profile image
Benjamin Delespierre • Edited

Dealing with thousands of routes, we ended up doing the following:

  • never use the Route::resource helper, with lots of routes it does more harm than good
  • create one RouteServiceProvider per entity (e.g. ContractRouteServiceProvider)
  • isolate each group in a different method
  • methods look like this
    public function mapContract()
    {
        Route::middleware(['web', 'auth'])
            ->namespace($this->namespace)
            ->group(function () {
                Route::get('addworking/contract', [
                    'uses' => "ContractController@dispatcher",
                    'as'   => "addworking.contract.contract.dispatcher",
                ]);

With the same pattern everywhere, makes it super easy to find a route using its name or its URI :-)

Collapse
 
sanz profile image
Sanz

Thanks, I appreciate your feedback. This surely is a clean approach to structure routes.