Blog Detail

17

Aug
A Clean Object-based Alternative to Laravel Route Files cover image

arrow_back A Clean Object-based Alternative to Laravel Route Files

Laravel Route Registrars is an amazing package that introduces a clean object-based way to define your routes in a Laravel application.

Installation

You can install this package via composer.

$ composer require olliecodes/laravel-route-registrars

Fresh Laravel Installation

If you’re installing this package on a fresh laravel installation, you’ll want to run the following command before you do anything with your routes.

php artisan init:routing

This will overwrite the app/Providers/RouteServiceProvider.php file with one compatible with the route registrars, and create default route registrars to replace both routes/web.php and routes/api.php.

Usage

To register new routes, you can either add their definitions to the map method of a RouteRegistrar, or create a new one.

Creating a new Registrar

The following command will create a new registrar inside app/Http/Routes.

php artisan make:registrar {name}

The {name} can be any valid class name, or sub-namespace. For example, using Auth\GuestRoutes will create app/Http/Routes/Auth/GuestRoutes.php.

There are several options available when creating a registrar.

–C|hasChildren

Create a route registrar that has the MapRouteRegistrars trait so that it can map child registrars.

–W|web

Create the route registrar in app/Http/Routes/Web, an option left in for those of you that are splitting the Web and API routes.

–A|API

Exactly the same as the above option, except it creates it in app/Http/Routes/Api

Registering Registrars

Any class that wants to register registrars can use the following trait.

OllieCodes\Registrars\Concerns\MapsRouteRegistrars

Once doing so, there are three ways to register. All of them require an instance of the following class.

Illuminate\Contracts\Routing\Registrar

This interface is implemented by the Laravel Router class, so you can use that.

Register multiple

Call the following method with an instance of the laravel router, and an array of fully qualified class names for the registrars.

mapRouteRegistrars(Registrar $router, array $registrars)

Register one

Call the following method with an instance of the laravel router, and the fully qualified class name of the registrars.

mapRouteRegistrar(Registrar $router, string $registrar)

For more details and source code, please Visit Github.

Published at : 17-08-2022

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project