In Laravel 11, if you want to set a default namespace for your routes so that you don't have to specify the full namespace each time you define a route, you can do so in the RouteServiceProvider class. Here's how you can set it up:
-
Open the
RouteServiceProvider.phpfile located in theapp/Providersdirectory. -
In the
RouteServiceProviderclass, you will find abootmethod. You can set the default namespace for your routes within this method by using the->namespace()method on theRoutefacade.
Here's an example of how to set the default namespace:
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
// ...
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
// ...
// Set the default namespace for the routes.
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
// ...
}
// ...
}
With this setup, you can now define your routes in routes/web.php without needing to specify the full namespace each time:
<?php
use Illuminate\Support\Facades\Route;
// You can now use the controller name directly without the full namespace.
Route::get('/', 'PageController@welcome');
This tells Laravel to prefix the namespace App\Http\Controllers to your controller classes when resolving them in your routes, allowing you to reference them with their short names as shown above.