How you can define custom route files within Laravel 11 new application structure

Spread the love

Moving to Laravel 11 and observing a more simplified application architecture? Those days of finding a collection of route files in the routes directory by default are long gone. Today, we’ll look into the process of defining custom route files within the new structure of Laravel.

Use the Class Blade Directive to apply classes in Laravel for better readability and maintainability in you code while working with Blade.

Wait, What Changed In Laravel 11?

With the release of Laravel 11, there have been significant changes to the default application structure. The emphasis focuses on minimalism, with certain files (such as middleware) being relocated from the app directory. You might be curious about the placement of custom routes now.

The Magic of bootstrap/app.php

The solution can be found in a vital configuration file: bootstrap/app.php. This file determines how Laravel routes are loaded.

Let’s see how to configure bootstrap/app.php to include a custom route file named dev.php:

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Support\Facades\Route;

return Application::configure(basePath: dirname(__DIR__))
  ->withRouting(
    web: __DIR__ . '/../routes/web.php',
    commands: __DIR__ . '/../routes/console.php',
    then: function () {
      if (app()->environment('local')) {
        Route::middleware('web')
          ->group(base_path('routes/dev.php'));
      }
    }
  );

Here’s a breakdown of the magic:

  • withRouting: This section configures route loading.
  • Custom Route Definition: We utilize the closure to define our custom route behavior.
  • Conditional Loading: In this example, the dev.php route file is only loaded in the local development environment using app()->environment('local'). You can adjust this condition as needed.
  • group and Middleware: The custom routes within dev.php are wrapped in a group with the web middleware, ensuring they follow the same conventions as your web routes.

Conclusion

Although the structure of Laravel may appear different initially, rest assured that defining custom routes is still fully supported. By making adjustments to the bootstrap/app.php configuration, you can effectively maintain organization in your project.