What is RouteServiceProvider?
It's a class for defining your routes and loaded by Laravel framework very early in the app lifecycle, so it's easy to load some configuration files. In this class, there's a method boot()
where we can define our custom function.
Laravel RouteServiceProvider
class, helps you to know where your routes files are. For your web routes and api routes the entry points are defined here.
Here in this class, we defined controllers default path or namespace. When you say namespace it means where a a certain controller could be found.
Namespace and Middleware
And let's take a look at the namespace for all the controllers
protected $namespace = 'App\Http\Controllers';
So this class also tells you where to find all your defined controllers. So the controllers have to be in App->Http->Controllers
Here web and api routes are protected with middleware.
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
In the above code, you see that, we have a web
middleware and then the namespace
. It means when you make web request which means directly visiting your applicaiton from web or browser, it would go through web middleware.
And routes for the web app must be define under App\Http\Controllers
path.
Complete code
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
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()
{
//
parent::boot();
}
/**
* Define the routes for the application.
*
* @return void
*/
public function map()
{
$this->mapApiRoutes();
$this->mapWebRoutes();
//
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* @return void
*/
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* @return void
*/
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
}
More about RouteServiceProvider
Here I will talk more about additional configuration for Laravel RouteServiceProvider. This changes you need to do, if you are using Laravel 10 or above. With this you have also complete control over namespace and Route::group().
The below video is part of another tutorial. But I put it here to increase your knowledge better about RouteServiceProvider.