DEV Community

Morcos Gad
Morcos Gad

Posted on

Custom Route Files - Laravel

Sometimes we want to put our Route in a different file than the web.php file in order to be more organized. Today we will learn how to create a new Route file

  • Create a new routes/static.php file (the name is arbitrary)
// File routes/static.php
Enter fullscreen mode Exit fullscreen mode
  • Add a middleware stack to app/Http/Kernel.php
// File app/Http/Kernel.php

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
        //add
        'static' => [
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ], 
    ]; 
Enter fullscreen mode Exit fullscreen mode
  • Update app/Providers/RouteServiceProvider.php to load our new route file, and apply our new middleware stack
// File app/Providers/RouteServiceProvider.php
     /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));
            //add
            Route::middleware('static')
                ->namespace($this->namespace)
                ->group(base_path('routes/static.php'));
        }); 
    }
Enter fullscreen mode Exit fullscreen mode

I hope you enjoyed the code and this method will help you in your future projects .

Top comments (0)