Laravel

Laravel 8+ redirect to previous page after login (Examples)

Share your learning

Hi, everyone, today we are going to discuss how to redirect users to the previous page after login. So, Intended page or Intended URI means the last page which we want to keep, remember and return the user to that page after successful login or authorization. 

This process can be authorization via login, any kind of payment or other verification task which the user needs to fulfill and return back to the intended page. 

We can achieve this, by using below steps with given examples,

Step 1: Set Intended URL

We can’t use redirect back() from login requests because that will redirect users to the login form again. Instead of this, we have to set up the intended url while user reach to login page then after login attempt, we can return user back to his intended url.

Now, for an example, we have some pages which are only accessible to the authorized user. To secure these pages we can use Auth middleware on their routes. So, if unauthorized user try to click on the page link, he will redirect back to the login form by this middleware

Got it! Hope you understand the above scenario, if not, read again.

Set the intended URL from the auth middleware as given in the below sample code.

<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Support\Facades\Redirect;

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()) {
            Redirect::setIntendedUrl($request->getUri());
            return route('login');
        }
    }
}

Step 2: Redirect to the intended URL

In the latest laravel, we have a trait on the LoginController Illuminate\Foundation\Auth\AuthenticatesUsers which clearly used the intended url after successful login. So, we don’t need to do anything here.

The below code is used in this trait as per syntax redirect()->intended(‘/default-path’)

/**
     * Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
     */    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        if ($response = $this->authenticated($request, $this->guard()->user())) {
            return $response;
        }

        return $request->wantsJson()
                    ? new JsonResponse([], 204)
                    : redirect()->intended($this->redirectPath());
    }

Laravel Intended URL with Ajax Example

The intended URL setup will be the same as given in the above steps. Here, we just need to modify the login response for ajax call like below example code.

$url = Redirect::intended(‘/default-path’)->getTargetUrl();

We need to return this url in the login response and then in the ajax success function we can redirect the user to this url.

Window.location = url

That’s it, see you in the next tutorial.

Satpal

Recent Posts

How to Switch PHP Versions in XAMPP Easily: Managing Multiple PHP Versions on Ubuntu

Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…

1 year ago

How to Use Coding to Improve Your Website’s SEO Ranking?

Let's understand about how to use coding to improve your website's SEO. In today’s computerized…

1 year ago

Most Important Linux Commands for Web Developers

Let's understand the most important linux commands for web developers. Linux, as an open-source and…

1 year ago

Top 75+ Laravel Interview Questions Asked by Top MNCs

Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…

1 year ago

Mailtrap Integration for Email Testing with Laravel 10

Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…

1 year ago

Firebase Cloud Messaging (FCM) with Ionic 6: Push Notifications

Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…

1 year ago