Search code examples
phplaravelhttp-redirectmiddleware

Laravel Redirect To Intended URL After Registration


When a user registers on my Laravel website, it automatically brings them to the dashboard (which is what I want). However, I created middleware for a specific page that redirects guest users to the register page. When the registration is completed, I want the user to be redirected back to the specific page they were trying to visit before they were redirected by the middleware. If the user was not redirected by this specific middleware, I still want the default page to be the dashboard after the user registers.

RegisterController:

protected $redirectTo = 'dashboard';

public function redirectTo(){
    return redirect()->intended($this->redirectTo)->getTargetUrl();
}

Middleware:

public function handle($request, Closure $next)
{
    if (auth()->guest()) {
        return redirect()->route('register');
    }
    return $next($request);
}

Solution

  • You can try setting the "intended URL" by using the guest method of the Redirector, "Create a new redirect response, while putting the current URL in the session.":

    return redirect()->guest(route('register'));