Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a namespace for Laravel 8 routes [duplicate]

Tags:

php

laravel

Question about routing in Laravel 8.x

Now Im adding such lines in web.php file:

use App\Http\Controllers\FirstController;
use App\Http\Controllers\SecondController;
use App\Http\Controllers\ThirdController;

and then just working on FirstController::class etc.

Is it wrong to use just namespace App\Http\Controllers; instead of all use lines one after another x times at the beggining?

Thanks.

like image 507
Arek TG Avatar asked Sep 23 '20 23:09

Arek TG


1 Answers

Instead, I would simply uncomment this line in app/Providers/RouteServiceProvider.php which will revert back to the Laravel <8 behavior of automatically prefixing route declarations in 'routes/web.php' 'routes/api.php' with the App\Http\Controllers namespace.

/**
 * The controller namespace for the application.
 *
 * When present, controller route declarations will automatically be prefixed with this namespace.
 *
 * @var string|null
 */
 protected $namespace = 'App\\Http\\Controllers';

This commented out property might not be in your app/Providers/RouteServiceProvider.php if you created the project when v8 was first released, (seems it was removed then added back) if not, just add it and uncommnet, and make sure its used in the boot method the prop and it'll work.

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

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

        Route::middleware('web')
            ->namespace($this->namespace)            // make sure this is present
            ->group(base_path('routes/web.php'));
    });
}
like image 99
Wesley Smith Avatar answered Sep 30 '22 16:09

Wesley Smith