Laravel 8 Redirect User to Previous Page After Login

Sep 18, 2021 . Admin



Hi Dev,

Today, in this article I will share something new about how actually work to redirect users to the previous page after login with laravel 8.I will create simple auth using laravel/ui.

First of all i will exaplain previous example how to create simple authentication using laravel-ui you will learn this first follow this article

So, in this example i will create laravel redirect to requested url after login simple authentication while user login redirect to previous page(home) page.

Here, laravel redirect to intended URL after login, laravel redirect to requested URL after login, redirect to the same page after login laravel, laravel 8 redirect to the previous page after login, laravel 8 redirect to previous page after login.

Here,i will give you a simple and easy example of how to implement laravel redirect to the intended URL after login simply follows my all steps.

Step 1: Download Laravel

Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app
Step 2 : Setup Database Configuration

After successfully install laravel app next we configure databse setup. We will open ".env" file and change the database name, username and password in the env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password
Step 3 : Create Auth using scaffold

Now, in this step, we will create auth scaffold command to create login, register and dashboard. so run following commands:

composer require laravel/ui

After, that you can run following command and check ui commands info.

php artisan ui --help

Next, You can use the following commands for creating auth:

Using Bootstrap:

php artisan ui bootstrap --auth
npm install
npm run dev
Method 1 : Show Login Form

After successfully run the above command. add showLoginForm() method in LoginController. This function will set the “url.intended” session variable So, let's copy bellow code and put it on LoginController.php file.

app/Http/Controllers/Auth/LoginController.php
/**
 * Write Your Code..
 *
 * @return string
*/
public function showLoginForm()
{
    if(!session()->has('url.intended'))
    {
        session(['url.intended' => url()->previous()]);
    }
    return view('auth.login');
}

Method 2 : Show Login Form

Here, In this second method, We have to add __contruct() method in redirect previous url or page inside LoginController.

$this->redirectTo = url()->previous();
app/Http/Controllers/Auth/LoginController.php
/**
 * Write Your Code..
 *
 * @return string
*/
public function __construct()
{
    $this->middleware('guest')->except('logout');
    $this->redirectTo = url()->previous();
}

It will help you...

#Laravel 8 #Laravel