简体   繁体   中英

Redirect user to login page when session expires in Laravel

I am trying to redirect a user back to the login page if their session has expired. I am using Laravel 5.5. I have edited my RedirectIfAuthenticated file to include the following code in the handle function:

if (!Auth::check()) {
    return redirect()->route('login', ['account' => 'demo']);
}

When I do this, I am receiving the following error message:

Missing required parameters for [Route: login] [URI: /].

My login route is inside a subdomain route group which is why I am passing the account parameter. Here is part of my code in web.php

// Subdomain routing
Route::domain('{account}.ems.dev')->group(function () {
    Route::get('/', 'LoginController@show')->name('login');
}

And here is my LoginController@show code:

/*
 * Show the login form
 */
public function show($account) {
    // Validate this is a valid subdomain
    $organization = Organization::where('subdomain', $account)->first();

    if ($organization) { 
        return view('login');
    } else {
        return 'This account does not exist.';
    }
}

Nothing I have tried works. I keep getting the exact same error message even though I am passing in the required parameters.

Update #1

Screenshot of error page:

在此输入图像描述

Update #2

After a little digging around the Whoops! error page, I see this, protected function unauthenticated is what is causing the problem:

在此输入图像描述

How do I override this function to add the missing parameter?

You can override the unauthenticated() method in your app/Exceptions/Handler.php file to add the missing route parameter.

use Illuminate\Auth\AuthenticationException;

class Handler extends ExceptionHandler
{
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        return $request->expectsJson()
            ? response()->json(['message' => $exception->getMessage()], 401)
            : redirect()->guest(route('login', ['account' => $request->route('account')]));
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM