DEV Community

Debajyoti Das
Debajyoti Das

Posted on

Creating new route file in Laravel

Best approach:
web.php

Route::prefix('company')->as('company:')->group(
    base_path('routes/company.php'),
);
Enter fullscreen mode Exit fullscreen mode

Access URL: http://localhost:8000/company/random
The below isn't a very good approach:
RouteServiceProveider.php

public function boot()
    {
        $this->configureRateLimiting();

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

            Route::middleware('web')
                ->group(base_path('routes/web.php'));

            Route::middleware('company')
                ->group(base_path('routes/company.php'));
        });
    }
Enter fullscreen mode Exit fullscreen mode

Middleware/Kernel.php

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::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,
        ],

        'company' => [
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ]
    ];
Enter fullscreen mode Exit fullscreen mode

routes/company.php

<?php

use Illuminate\Support\Facades\Route;

Route::get('/company', function(){
    return 'In Company';
});

Route::get('/random1', function(){
    return 'In Company';
});
Enter fullscreen mode Exit fullscreen mode

Now localhost:8000/company will hit routes in this file

Image description

Top comments (0)