gpt4 book ai didi

laravel - 将 Auth 中间件应用于所有 Laravel 路由

转载 作者:行者123 更新时间:2023-12-02 16:40:47 24 4
gpt4 key购买 nike

当我在所有 Controller 中应用身份验证中间件时,对除登录和注册之外的所有路由进行身份验证的正确方法是什么?有没有一种方法可以在一个地方应用身份验证中间件并排除登录、注册路由?

最佳答案

您可以通过将中间件添加到 RouteServiceProvider 中的路由映射来将中间件添加到整个 web.php 路由文件中。

转到 app/Providers/RouteServiceProvider.php 并在 mapWebRoutes() 中,将 middleware('web') 更改为 中间件(['web','auth']):

protected function mapWebRoutes()
{
Route::middleware(['web', 'auth'])
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
<小时/>

这是(不是?)完全不相关的,但这里有一个示例,它是一种处理大量路由文件的干净方法,而不是将所有路由放入单个 web.php 文件:

创建一个新方法mapAdminRoutes():

protected function mapAdminRoutes()
{
Route::middleware(['web', 'auth:admin'])
->namespace('App\Http\Controllers\Admin')
->name('admin.')
->group(base_path('routes/admin.php'));
}

映射它:

public function map()
{
$this->mapWebRoutes();
$this->mapAdminRoutes(); // <-- add this
...
}

routes 文件夹中创建一个 admin.php 文件,然后为 Admin 创建路由:

<?php

use Illuminate\Support\Facades\Route;

// This route's name will be 'admin.dashboard'
Route::get('dashboard', 'DashboardController@dashboard')->name('dashboard');

// This route's name will be 'admin.example'
Route::get('example', 'ExampleController@example')->name('example');

...

现在您可以在 1 个位置配置所有内容,例如前缀名称中间件命名空间

检查php artisan route:list以查看结果:)

关于laravel - 将 Auth 中间件应用于所有 Laravel 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54198483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com