Using Route Registrars in your Laravel application

Published on by

Using Route Registrars in your Laravel application image

Recently I came across a unique approach to loading routes into Laravel applications, and I wanted to share this with you. It allows you to create Route Registrars classes you register your routes within. I saw this in a package currently being developed by Ollie Read, and it caught my attention as a clean and exciting way to register routes.

The changes required to your standard Laravel application are relatively simple. We make a few changes to the Route Service Provider - and remove the web and API route files. The first thing we do is create a new trait/concern that we can add to our app/Providers/RouteServiceProvider called MapRouteRegistrars. Add the following code to this new trait/concern.

declare(strict_types=1);
 
namespace App\Routing\Concerns;
 
use App\Routing\Contracts\RouteRegistrar;
use Illuminate\Contracts\Routing\Registrar;
use RuntimeException;
 
trait MapRouteRegistrars
{
protected function mapRoutes(Registrar $router, array $registrars): void
{
foreach ($registrars as $registrar) {
if (! class_exists($registrar) || ! is_subclass_of($registrar, RouteRegistrar::class)) {
throw new RuntimeException(sprintf(
'Cannot map routes \'%s\', it is not a valid routes class',
$registrar
));
}
 
(new $registrar)->map($router);
}
}
}

As you can see, we also need to create an interface/contract to use and ensure all of our Registrars implement it. Create this under app/Routing/Contracts/RouteRegistrar and add the following code.

declare(strict_types=1);
 
namespace App\Routing\Contracts;
 
use Illuminate\Contracts\Routing\Registrar;
 
interface RouteRegistrar
{
public function map(Registrar $registrar): void;
}

Now that we have the trait and interface in place, we can look at the changes we need to make to the default Route Service Provider.

declare(strict_types=1);
 
namespace App\Providers;
 
use App\Routing\Concerns\MapsRouteRegistrars;
use Illuminate\Contracts\Routing\Registrar;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
 
class RouteServiceProvider extends ServiceProvider
{
use MapsRouteRegistrars;
 
protected array $registrars = [];
 
public function boot(): void
{
$this->routes(function (Registrar $router) {
$this->mapRoutes($router, $this->registrars);
});
}
}

From the above code, you can see that we have added a new property to our route service provider. This property is where the application's route registrars are registered and loaded inside the boot method.

Now that we have got our application ready to use route registrars instead of route files, let's create a default one for our application. This approach would work exceptionally well in a domain-driven design or modular system - allowing each domain or module to register its routes. For this example, we will keep this simple so that you can understand the approach. Create a new route registrar in app/Routing/Registrars/DefaultRegistrar.php and add the following code.

declare(strict_types=1);
 
namespace App\Routing\Registrars;
 
use App\Routing\Contracts\RouteRegistrar;
 
class DefaultRegistrar implements RouteRegistrar
{
public function map(Registrar $registrar): void
{
$registrar->view('/', 'welcome');
}
}

Now that our default registrar is created, we can register this inside our Route Service Provider, ensuring it is loaded.

declare(strict_types=1);
 
namespace App\Providers;
 
use App\Routing\Concerns\MapsRouteRegistrars;
use App\Routing\Registrars\DefaultRegistrar;
use Illuminate\Contracts\Routing\Registrar;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
 
class RouteServiceProvider extends ServiceProvider
{
use MapsRouteRegistrars;
 
protected array $registrars = [
DefaultRegistrar::class,
];
 
public function boot(): void
{
$this->routes(function (Registrar $router) {
$this->mapRoutes($router, $this->registrars);
});
}
}

Now, if you visit /, you will be loaded with the welcome view, which means that everything is all hooked up correctly. I can imagine a great way that I might utilize this in an application of mine, where I have static marketing routes, blog routes, admin routes, and more. As an example, I would imagine the route service provider looking like the following:

declare(strict_types=1);
 
namespace App\Providers;
 
use App\Routing\Concerns\MapsRouteRegistrars;
use App\Routing\Registrars\AdminRegistrar;
use App\Routing\Registrars\BlogRegistrar;
use App\Routing\Registrars\MarketingRegistrar;
use Illuminate\Contracts\Routing\Registrar;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
 
class RouteServiceProvider extends ServiceProvider
{
use MapsRouteRegistrars;
 
protected array $registrars = [
MarketingRegistrar::class, // Marketing Routes
BlogRegistrar::class, // Blog Routes
AdminRegistrar::class, // Admin Routes
];
 
public function boot(): void
{
$this->routes(function (Registrar $router) {
$this->mapRoutes($router, $this->registrars);
});
}
}

Splitting our routes like this is a great way to move from a standard PHP routes file to a class-based routing system allowing for better encapsulation with your application or domain.

What other ways have you found to help you manage a growing application? Especially from a routing perspective, they can get a little unruly after a while. Let us know on Twitter.

Steve McDougall photo

Technical writer at Laravel News, Developer Advocate at Treblle. API specialist, veteran PHP/Laravel engineer. YouTube livestreamer.

Cube

Laravel Newsletter

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

image
Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes.

Visit Larafast: Laravel SaaS Starter Kit
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
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
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
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
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

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
All Green logo

All Green

All Green is a SaaS test runner that can execute your whole Laravel test suite in mere seconds so that you don't get blocked – you get feedback almost instantly and you can deploy to production very quickly.

All Green
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with VILT and TALL stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a 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
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Asserting Exceptions in Laravel Tests image

Asserting Exceptions in Laravel Tests

Read article
Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4 image

Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4

Read article
Basset is an alternative way to load CSS & JS assets image

Basset is an alternative way to load CSS & JS assets

Read article
Integrate Laravel with Stripe Connect Using This Package image

Integrate Laravel with Stripe Connect Using This Package

Read article
The Random package generates cryptographically secure random values image

The Random package generates cryptographically secure random values

Read article
Automatic Blade Formatting on Save in PhpStorm image

Automatic Blade Formatting on Save in PhpStorm

Read article