Laravel Redirect to Previous (Intended) Page After Registration

Published Apr 21, 20212 min read

Every once in a while, you'll have a protected route that only registered users have access to. For example, you might have a webshop where users can add items to cart only when they are registered or have a subscription service with the exact requirements.

What happens is a typical scenario, your user will click on something only registered users can access to, and you'll redirect them to the registration page; you can do that like this:

if(auth()->guest()) return redirect()->guest('register'); 

But what to do after the registration? Well, Laravel has a lot of little gems that might not be so obvious. To achieve the redirect to the previous/intended page you can use a registered() method in Registration Controller like this:

protected function registered(Request $request, $user)
{
    return redirect()->intended($this->redirectPath());
}

This is what the above guest method does under the hood:


    /**
     * Create a new redirect response, while putting the current URL in the session.
     *
     * @param  string  $path
     * @param  int  $status
     * @param  array  $headers
     * @param  bool|null  $secure
     * @return \Illuminate\Http\RedirectResponse
     */
    public function guest($path, $status = 302, $headers = [], $secure = null)
    {
        $request = $this->generator->getRequest();

        $intended = $request->method() === 'GET' && $request->route() && ! $request->expectsJson()
                        ? $this->generator->full()
                        : $this->generator->previous();

        if ($intended) {
            $this->setIntendedUrl($intended);
        }

        return $this->to($path, $status, $headers, $secure);
    }
    

As you can see, it sets the intended URL and redirects to the provided path. With the redirect URL specified in session, your registered() method will know where to return the user to.

That's it, two lines that can save you some time the next time you need to redirect to the intended route.