What is Remember Me?

The Remember Me feature allows the client-side users to automatically remember their user login details as they regularly visit the website. In most cases, the user login information is store in the form of a cookie.

To view remember me cookie in your Laravel application click on i-icon besides URL field and then select cookie dropdown in Google Chrome and to find in Mozilla Firefox goto inspect element by right-clicking mouse and after clicking on inspect element goto storage tab there you will find cookies used by your laravel site under option cookies.

How to implement remember Me functionality in your Laravel Application

If you take a look at official laravel documentation then there is clearly mentioned then you can set the browser to remember user by passing a boolean value as the second argument to Auth::attempt($credentials, $remember_me). The default value of remembers me argument is set to FALSE.

In users table, you’ll also find a remember_token column which contains encrypted string on user information.

Here is the main snippet for remembering user.

// In LoginController.php
$credential = [
    'email' => $request->email,
    'password' => $request->password,
];

$remember_me  = ( !empty( $request->remember_me ) )? TRUE : FALSE;

if(Auth::attempt($credential)){
    $user = User::where(["email" => $credential['email']])->first();

    Auth::login($user, $remember_me);

    // redirect authenticated user to another page
}

Here the $request->remember_me gets value from a checkbox and if user checks on checkbox than remember_me will have a boolean value TRUE else FALSE.

Complete Source Code:

User Model

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    /**
        * The attributes that are mass assignable.
        *
        * @var array
        */
    protected $fillable = [
        'first_name', 'last_name', 'name', 'email', 'password',
    ];

    /**
        * The attributes that should be hidden for arrays.
        *
        * @var array
        */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
        * The attributes that should be cast to native types.
        *
        * @var array
        */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

The above is the snippet of the default user model provided by Laravel out of the box.

#laravel #php #laravel #php

Implement Laravel Remember Me Functionality in Your Web Application
157.75 GEEK