无法从自定义路由文件访问 Auth::user() ? Laravel 7

Can't access the Auth::user() from a custom route file ? Laravel 7

出于某种目的,我决定为管理员创建一个单独的路由文件并将其逻辑与 web.php 分开,但我却面临这个问题:

//admin.php ( routing file )


<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth

    Route::get('/admin', function ()
            {
                dd(Auth::user());  //return null
            });

ps:admin.php注册在RouteServiceProvider

public function map()
    {
        $this->mapApiRoutes();
        $this->mapWebRoutes();
        $this->mapAdminRoutes();
         //
    }

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

让我们尝试在 config/auth 中定义新路由。php

'guards' => [
    'admin' => [
        'driver' => 'session',
        'provider' => 'users',
    ]
],

因为您想获取会话来检查身份验证。 所以让我们试试这个。

添加网络中间件

Route::middleware(['web','admin'])->...