I just added this route group to web.php
:
Route::middleware('auth')->group(function() {
Route::get('profile' , [ProfileController::class, 'index'])->name('profile');
});
As you can see I have used the middleware auth
so if I'm not logged in, it should be showing me the login page.
And I had also defined authentication routes manually:
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']);
});
So the route name of the login page is auth.login
and I just added it to Authenticate
middleware which is set to auth
at kernel.php
:
'auth' => \App\Http\Middleware\Authenticate::class,
Authenticate.php
:
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('auth.login');
}
}
Now, the problem is whenever it should showing me the login page when not signed in, I get this error message:
Symfony\Component\Routing\Exception\RouteNotFoundException Route [login] not defined.
So what's going wrong here, how can I fix this error?
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'));
}
Just change this
Route::get('login' , [LoginController::class, 'showLogin'])->name('auth.login');
to this
Route::get('login' , [LoginController::class, 'showLogin'])->name('login');
This sounds ridiculous but true. The reason is when you call login you call it with
auth.login
but Laravel knows onlylogin
. I had a similar issue and able to sort it by defining another route(GET).
Laravel uses login
route somewhere for example in \app\Http\Handler.php
therefore it's necessary to have login route. You can change your route name as Abdulla Nilam
said before or If you don't want to change it, add this:
Route::get('/login/redirect', function () {
return redirect(route('auth.login'));
})->name('login');
( Laravel 8 ) In 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');
}
}
}
you can easily change " login " to " auth.login " !
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.