support@codebucket.net

Implement Remember Me in Laravel with Cookie

Implement Remember Me in Laravel with Cookie

K. M. Shawkat Zamil | January 11, 2023

Hello Developers,

 

Laravel manages its own Remember Me feature. But Sometimes this feature is not working in the custom authentication function. To solve this we will use our browser cookie. In the Login form, we have a remember me check box.

 

 

Then we will create a cookie in the browser.

 

 

Finally, we will show how to implement it. To do so, first thing first, install a Laravel project.

 

Install Laravel Project In Your Environment

 

First, you need to go to your development workspace. My workspace is situated in D:/ drive. Open a command prompt and write the below code to install Laravel.

 

laravel new example-app

 

Database Configuration

 

After installing the project, open the project in your code editor. Now we have to configure the database credentials. As I am using the wamp server, I have to start the server and open the localhost/phpmyadmin. In there I will create a database named example-app.

 

 

After that, add the credentials to the project .env file

 

/.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=example-app
DB_USERNAME=[USERNAME]
DB_PASSWORD=[PASSWORD]

 

Install Bootstrap Scaffolding

 

Any Laravel project will include Bootstrap and auth scaffolding. To initiate let's run the below command:

 

composer require laravel/ui

 

To make the laravel default bootstrap login design run the below command:

 

php artisan ui bootstrap --auth

 

Lastly, install the npm in the project. To do so, run the two commands one by one.

 

npm install 


npm run dev

 

Also, run the mix command to get the design:

 

npm run watch

 

Finally, you can run the php artisan migrate In the command prompt run the below command:

 

php artisan migrate

 

Sometimes you might get the below error:

 

SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes

 

 If you  get the error, simply add the following line in the [project_directory]/app/Providers/AppServiceProvider.php

 

/app/Providers/AppServiceProvider.php

use Illuminate\Support\Facades\Schema;

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Schema::defaultStringLength(191);
}

 

As your table has already been generated. Now run the php artisan migrate:fresh. To store cookies in the browser, add cookie in the session.php file.

 

 

/config/session.php

'driver' => env('SESSION_DRIVER','cookie')

 

Create an Authentication controller to make the functions. Run the below command in the project route.

 

php artisan make:controller AuthenticationController

 

Create two routes for login and login submit functions in the route file.

 

/routes/web.php

use App\Http\Controllers\AuthenticateController;

Route::get('login', [AuthenticateController::class, 'login'])->name('login');
Route::post('make_login', [AuthenticateController::class, 'make_login'])->name('make_login');

 

Then we have to add remember me select box in the form. in my case, I have a post function named make_login. The form is:

 

/resource/views/login.blade.php

<form method="POST" action="{{ route('make_login') }}">
    @csrf
    <div class="form-group mb-4">
        <label for="email" class="fs-6 text text-black-50">Email Adress</label>
        <input type="email" name="email" id="email" class="form-control rounded-1 @error('email') is-invalid @enderror" value="{{ old('email') }}" autofocus required>
        @error('email')
                <span class="invalid-feedback" role="alert">
                    <strong>{{ $message }}</strong>
                </span>
            @enderror
    </div>
    <div class="form-group mb-3">
        <label for="password" class="fs-6 text text-black-50">Password</label>
        <input type="password" name="password" id="password" class="form-control rounded-1  @error('password') is-invalid @enderror" value="{{ old('password') }}" required
            aria-autocomplete="list">
            @error('password')
                <span class="invalid-feedback" role="alert">
                    <strong>{{ $message }}</strong>
                </span>
            @enderror
    </div>
    <div class="d-flex mb-5 align-items-center justify-content-between">
        <div class="form-check">
            <input class="form-check-input" type="checkbox" name="remember_me" value="1"
                id="flexCheckIndeterminate">
            <label class="form-check-label fs-6 text text-black-50" for="flexCheckIndeterminate">
                Remember me
            </label>
        </div>
    </div>
    <div class="d-grid mb-4">
        <button type="submit" class="btn btn-primary border-0 rounded-5 p-3 px-3 text-uppercase fs-5 text">Sing
            In</button>
    </div>
</form>

 

In the submit, we will take the remember me a boolean response and pass in the Auth::attempt() like below:

 

app/Http/Controllers/AuthenticateController.php

public function make_login(Request $request)
{
    $request->validate([
        'email' => 'required',
        'password' => 'required',
    ]);

    $credentials = array(
        'email' => $request->input('email'),
        'password' => $request->input('password')
    );

    $remember_me = isset($request->remember_me) && $request->remember_me == 1 ? true : false;

    if (Auth::attempt($credentials, $remember_me)) {
        return redirect()->route('dashboard');
    } else {
        return redirect()->route('login');
    }
}

 

When we log in with the remember me check box then a cookie is set in the browser like below:

 

 

To check if our cookie exists or not, we have to check with the Cookie::has(Auth::getRecallerName()). We will show the login  page if our cookie does not exist otherwise show our dashboard like the below:

 

app/Http/Controllers/AuthenticateController.php

public function login()
{
    if (Cookie::has(Auth::getRecallerName())) {
        return redirect()->route('dashboard');
    } else {
        return view('login');
    }
}

 

That's how we implement the Remember Me feature in Laravel with cookies. Hope this might help in the journey of development.

 

Read More: How to Configure Laravel Default Email Verification

 

K. M. Shawkat Zamil

K. M. Shawkat Zamil

Senior Software Engineer

I am a Senior Software Engineer in a reputed company in Bangladesh. I am a big fan of Laravel, PHP Programming, MSSQL Server, MySql, JavaScript, and lots more. I love to help people who are especially eager to learn. I believe in patience and motivation.