Blog Detail


Discover Routes Automatically with Laravel Route Discovery cover image

arrow_back Discover Routes Automatically with Laravel Route Discovery

The Laravel-route-discovery is a package by Spatie that can automatically discover routes for controllers and views in your Laravel application. This isn’t an all-in approach. While using use auto-discovery, you can still register routes like you’re used to. The laravel-route-discovery package requires PHP 8.0+, Laravel 8+.

// typically in a routes file


// other routes

Using PHP attributes you can manipulate discovered routes: you can set a route name, add some middleware, or …

Here’s how you would add middleware to a controller whose’s route will be auto-discovered.

namespace App\Http\Controllers;

use Illuminate\Routing\Middleware\ValidateSignature;
use Spatie\RouteDiscovery\Attributes\Route;

class MyController
    #[Route(middleware: ValidateSignature::class)]
    public function myMethod() { /* ... */ }

Installation & setup

You can install the package via composer:

composer require spatie/laravel-route-discovery

Publishing the config file

Optionally, you can publish the route-discovery config file with this command.

php artisan vendor:publish --tag="route-discovery-config"

Getting started

This package can automatically discover and register routes for a directory containing controllers.

Via the routes file

You can enable route discovery via the routes file.

// in a routes file

use Spatie\RouteDiscovery\Discovery\Discover;


Via the config file

Alternatively, you can discover routes using the config file.

First, you need to publish the config file. This will create a file at config/route-discovery.php

php artisan vendor:publish --tag="route-discovery-config"

In the discover_controllers_in_directory key of the route-discovery config file, you can specify a directory that contains controllers.

Here you can uncomment the line to register controllers in the app_path(‘Http/Controllers’) directory. Of course, you can use any directory you want.

// config/route-discovery

 * Routes will be registered for all controllers found in
 * these directories.
'discover_controllers_in_directory' => [
// ...

This package has a lot of other features like:

  • Mapping controllers to routes
  • Discovering routes for views
  • Mapping views to routes
  • Using route transformers

If you want to learn more about the features and usage of this package, you can visit its complete documentation & source code on Github.

Published at : 01-03-2022

Author : Rizwan Aslam
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