Laravel Auth: After-Registration Redirect to Previous (Intended) Page

Laravel Auth features a function to redirect logged-in user to the same page they were visiting before. So, for example, if you visit /posts, you get automatically redirected to /login and then enter your data successfully, Laravel will “remember” and redirect you back to /posts instead of default /home. But it doesn’t work with new user registration, let’s see how we can change it.

Imagine the scenario:

  • You visit /posts URL;
  • System uses ‘auth’ middleware and redirects you back to /login form;
  • But you don’t have a user yet, so you click Register and land on /register URL;
  • And then, after successful registration – you get redirected where? To default /home URL, or whatever is specified in $redirectTo property in RegisterController.

So, how to customize it and make Laravel “remember” previous page for registration, too? We will dive into how Auth works internally.

In fact, it already stores that information, we just need to use it.

If you dig deeper into the LoginController logic, it uses Trait AuthenticatesUsers.php from core Laravel’s /vendor folder. And it has this method:

public function login(Request $request)
{
    // ...

    if ($this->attemptLogin($request)) {
        return $this->sendLoginResponse($request);
    }

    // ...

}

Let’s dig deeper – what is sendLoginResponse()? Within the same Trait:

protected function sendLoginResponse(Request $request)
{
    // ...

    return $this->authenticated($request, $this->guard()->user())
            ?: redirect()->intended($this->redirectPath());
}

As you can see, it uses redirect()->intended() method. How does it work? Official Laravel documentation describes it like this:

The intended method on the redirector will redirect the user to the URL they were attempting to access before being intercepted by the authentication middleware.

Under the hood, its logic is in /vendor/laravel/framework/src/Illuminate/Routing/Redirector.php:

public function intended($default = '/', $status = 302, $headers = [], $secure = null)
{
    $path = $this->session->pull('url.intended', $default);

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

Now, let’s take a look at app/Http/Controllers/Auth/RegisterController.php, it also uses a Trait from the core:

trait RegistersUsers
{
    use RedirectsUsers;

    // ...

    public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create($request->all())));

        $this->guard()->login($user);

        return $this->registered($request, $user)
                        ?: redirect($this->redirectPath());
    }

Look at the last part of redirection. As you can see, it uses simple redirect(), without intended(). So this is the part we need to change.

But we can’t edit that directly in /vendor folder, what we do is we copy-paste the same Trait’s method into RegisterController, and change the redirection part:

class RegisterController extends Controller
{

    use RegistersUsers;

    // ...

    /**
     * Handle a registration request for the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create($request->all())));

        $this->guard()->login($user);

        return $this->registered($request, $user)
            ?: redirect()->intended($this->redirectPath());
    }

}

And, that’s it – now, after registration user will be redirected to the page they were visiting before ‘auth’ middleware restricted their access.

You can read more Auth “tricks” in these articles:

Like our articles?
Check out our Laravel online courses!

4 COMMENTS

  1. the above process to redirect a user coming from search engines to the registration page and then redirect back to the specific subpage the user wanted to see is NOT a good approach in an SEO point of view: Google sees the /login page as the most important page of the website because all subpages are redirecting/ linking to this registration page. Means your login page will rank the highest because it contains the highest amount of internal links. What you should do instead: create an interstitial in JS and exclude it for search engines via robots.txt

    • Thanks for the comment Alexander. I generally agree, but don’t you think that if the page is restricted by auth middleware, it means that it should NOT be indexed by search engines at all? And I haven’t seen any website with login being indexed as the first page, do you have an example? Cause I think you’re raising pretty artificial problem.

  2. In this case you are right!!
    But why not providing unique header titles and meta descriptions and index all sites on search engines to drive additional traffic?
    Then using an interstitial to gate content will help in visibility.

LEAVE A REPLY

Please enter your comment!
Please enter your name here