Discover Routes Automatically with Laravel Route Discovery

Discover Routes Automatically with Laravel Route Discovery cover image

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

Discover::controllers()->in($whateverDirectoryYouPrefer);
Discover::views()->in($whateverDirectoryYouPrefer);

// 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;

Discover::controllers()->in(app_path('Http/Controllers'));

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' => [
    app_path('Http/Controllers'),
],
// ...

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.

Written by

Rizwan Aslam

Founder and CEO of CodeBrisk, with years of experience building web applications with Laravel and leading a team of expert developers.

More about Rizwan
Book a free call
Book a call with CodeBrisk