Laravel authentication offers remember me functionality out of the box and to implement remember me feature in laravel we only need to follow some guidelines provided by laravel so in this article i will show you the simplest way to implement this. Most of the time while developing login functionality of application its required that to handle the remember me checkbox so that client do not need to keep login again and again on visiting the website back.
We will take a simple example of login form and submitting of it to laravel authentication. we will create a checkbox whether user want to remember the login or not and input box for email and password.
this example will work in any version of laravel 5, laravel 6, laravel 7, laravel 8, and laravel 9. So let’s begin the tutorial.
So there is 2 most important thing we need to do is as follow
Step 1 : Add remember_token column in your users table
In this step you need to add remember_token
in your users table so we can store the token on click of remember me checkbox so check your table first if its exist in users
table then okay otherwise you need to create it as follow
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Step 2 : Use Auth::attempt() method and Pass second argument as true
Now, use Auth::attempt()
and pass the second argument true
to enable the remember me functionality as follow
public function authnticate(Request $req)
{
$req->validate([
'email' => 'required|email|min:4|max:50',
'password' => 'required'
]);
$remember_me = $req->has('remember_me') ? true : false;
$check = $req->only('email', 'password');
if(\Auth::attempt($check, $remember_me))
{
return redirect('user/dashboard');
}
else
{
session()->put('error-msg', "Please enter the valid username and password");
return redirect('user/login');
}
}
Learn Also : Laravel 8 Custom login and registration with example or Laravel ajax login and registration with example