簡體   English   中英

Laravel 8:從身份驗證中間件重定向回后未定義路由登錄

[英]Laravel 8: Route login not defined after redirection back from auth middleware

我剛剛將此路由組添加到web.php

Route::middleware('auth')->group(function() {
    Route::get('profile' , [ProfileController::class, 'index'])->name('profile');
});

如您所見,我使用了中間件auth ,所以如果我沒有登錄,它應該向我顯示登錄頁面。

而且我還手動定義了身份驗證路由:

Route::prefix('auth')->namespace('Auth')->middleware('guest')->group(function() {
    Route::get('login' , [LoginController::class, 'showLogin'])->name('auth.login');
    Route::post('login' , [LoginController::class, 'login']);
    Route::get('register' , [RegisterController::class, 'showRegister'])->name('auth.register');
    Route::post('register' , [RegisterController::class, 'register']);
});

所以登錄頁面的路由名稱是auth.login ,我只是將它添加到Authenticate中間件中,該中間件在kernel.php處設置為auth

'auth' => \App\Http\Middleware\Authenticate::class,

Authenticate.php

protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('auth.login');
        }
    }

現在,問題是每當它在未登錄時向我顯示登錄頁面時,我都會收到以下錯誤消息:

Symfony\Component\Routing\Exception\RouteNotFoundException 路由[登錄] 未定義。

那么這里出了什么問題,我該如何解決這個錯誤?

app\Exceptions\Handler.php

use Illuminate\Auth\AuthenticationException;

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return redirect()->guest(route('auth.login'));
}

改變這個

Route::get('login' , [LoginController::class, 'showLogin'])->name('auth.login');

對此

Route::get('login' , [LoginController::class, 'showLogin'])->name('login');

這聽起來很荒謬,但卻是事實。 原因是當您調用 login 時,您使用auth.login調用它,但 Laravel 只知道login 我有一個類似的問題,並且能夠通過定義另一條路線(GET)對其進行排序。

路線

Laravel 在某處使用login路由,例如在\app\Http\Handler.php因此有必要有登錄路由。 您可以像Abdulla Nilam之前所說的那樣更改您的路線名稱,或者如果您不想更改它,請添加以下內容:

Route::get('/login/redirect', function () {
     return redirect(route('auth.login'));
})->name('login');

( Laravel 8 )在 App\Http\Middleware\Authenticate.php

    <?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('auth.login');
        }
    }
}

您可以輕松地將“登錄”更改為“ auth.login ”!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM