[英]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'));
}
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.