Tinkerwell - The PHP Scratchpad

Laravel Route Tips to Improve Your Routing

Published on by

Laravel Route Tips to Improve Your Routing image

The Laravel router has a great, well-polished API when you first dive into Laravel as a beginner or newcomer to the framework. What follows is not anything hidden or new, but a few tips that should help you when you’re learning Laravel 5.

The documentation is excellent, and the tips that follow supplement and piece together a few parts that will help you get a quick jumpstart on learning how to use routing in your Laravel applications.

Custom Namespaces

As outlined in the documentation, if you want a group of routes to use a namespace like App\Http\Controllers\Admin, you can define a namespace using the fluent routing API introduced in Laravel 5.4:

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

This is exactly the technique used in the RouteServiceProvider found in each Laravel project:

protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}

Because the routes/web.php file has a namespace, our Admin namespace relatively.

To create controllers in the App\Http\Controllers\Admin, you can run the following console command:

php artisan make:controller -r Admin/UsersController

Within our previous routing example, our definition might look like this in the routes/web.php file:

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

Route Macros

The Router is macroable, which means if you have a group of routes that you want to provide via a package or reusable groups of route definitions, you can define a macro in a service provider.

For example, maybe you have some shopping route for an e-commerce store that you ship as a package, and allow users to override or customize some parts of the routes:

// Inside a service provider boot()
 
public function boot()
{
Route::macro('shopRoutes', function ($prefix) {
Route::group([
'prefix' => $prefix,
'middleware' => ['shopping'],
], function () {
Route::get('products/{product}', 'ProductsController@show');
// ...
});
});
}

Then the consumer could call the macro in a new Laravel application within routes/web.php:

collect(config('languages'))->each(function ($language) {
Route::shopRoutes($language);
});

Or perhaps an alternate implementation might look like:

Route::macro('shopRoutes', function ($languages) {
Route::group([
'prefix' => '/{language}',
'middleware' => ['shopping'],
'where' => ['language' => implode('|', $languages)],
], function () {
Route::get('products/{product}', 'ProductsController@show');
// ...
});
});

The macro examples are abstract, but you get the idea. I would suggest that you only use route macros if it makes sense to your use-case. You’ll know when the timing is right!

Debugging Routes

I appreciate that in a Laravel application, the web.php file (and api.php file) is a self-documenting file about the routes to which my application is capable of responding. I prefer to define every route instead of using resources because I appreciate the documentation aspect of this file.

If you find yourself trying to find a route or debugging all possible defined routes, the artisan route:list command is helpful:

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

The route:list command is useful to see the name of the route and the attached middleware. Which brings me to the next tip, naming routes.

Named Group Routes

A common convention in Laravel is naming routes, which allows you to easily reference the name of the route and avoid hard-coding the root-relative URI in your templates. In some applications hard-coding the URI is fine, in other cases, the named routes allow the following:

{{ route('admin.users.show', ['user' => $user]) }}
{{-- /admin/users/2 --}}

When you are defining a group of routes, for example, our admin example, you can also prefix the name of the route on the group:

Route::namespace('Admin')
->prefix('admin')
->name('admin.')
->group(function () {
Route::resource('users', 'UsersController');
});

The above prefixed name would generate route names like the following for the users resource controller:

  • admin.users.index
  • admin.users.store
  • admin.users.create
  • admin.users.show
  • admin.users.update
  • admin.users.destroy
  • admin.users.edit

Learn More

Read through the entire routing documentation and the resource controllers section of the controllers documentation. I reference the resource controllers section to try and ensure that most of my routes represent a REST verb and for route naming conventions.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and more

Visit CodeRabbit
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Laravel 12.44 Adds HTTP Client afterResponse() Callbacks image

Laravel 12.44 Adds HTTP Client afterResponse() Callbacks

Read article
Handle Nested Data Structures in PHP with the Data Block Package image

Handle Nested Data Structures in PHP with the Data Block Package

Read article
Detect and Clean Up Unchanged Vendor Files with Laravel Vendor Cleanup image

Detect and Clean Up Unchanged Vendor Files with Laravel Vendor Cleanup

Read article
Seamless PropelAuth Integration in Laravel with Earhart image

Seamless PropelAuth Integration in Laravel with Earhart

Read article
Laravel API Route image

Laravel API Route

Read article
Laravel News 2025 Recap image

Laravel News 2025 Recap

Read article