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
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud
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 $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
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
Join the Mastering Laravel community logo

Join the Mastering Laravel community

Connect with experienced developers in a friendly, noise-free environment. Get insights, share ideas, and find support for your coding challenges. Join us today and elevate your Laravel skills!

Join the Mastering Laravel community
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
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
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
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
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Enhance Validation Testing Precision with Laravel's assertOnlyJsonValidationErrors image

Enhance Validation Testing Precision with Laravel's assertOnlyJsonValidationErrors

Read article
Generate HTTP Fixtures from Live API Calls in Laravel image

Generate HTTP Fixtures from Live API Calls in Laravel

Read article
Confidently Extract Single Array Items with Laravel's Arr::sole() Method image

Confidently Extract Single Array Items with Laravel's Arr::sole() Method

Read article
Safely Retry API calls in Laravel image

Safely Retry API calls in Laravel

Read article
Laravel's AsHtmlString Cast for Elegant HTML Attribute Management image

Laravel's AsHtmlString Cast for Elegant HTML Attribute Management

Read article
NativePHP for Mobile v1 — Launching May 2 image

NativePHP for Mobile v1 — Launching May 2

Read article