Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Today, I will give you an example of “How to Get users last login time in Laravel”, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application.
First, what we’re doing here, This is the example :
We will use Laravel Events to log each user’s login information, Laravel’s events provide a simple observer pattern implementation, allowing you to subscribe and listen for various events that occur within your application. Event classes are typically stored in the app/Events directory, while their listeners are stored in app/Listeners.
Events serve as a great way to decouple various aspects of our application since a single event can have multiple listeners that do not depend on each other. So, we’ll use Laravel Events to log each user’s login information.
Create a Listener
php artisan make:listener UpdateLastSignInAt
Edit the UpdateLastSignInAt listener to add the event handling logic.
app\Listeners\UpdateLastSignInAt.php
<?php
namespace App\Listeners;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Carbon\Carbon;
use Illuminate\Auth\Events\Login;
class UpdateLastSignInAt
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param object $event
* @return void
*/
public function handle($event)
{
$event->user->last_sign_in_at = $event->user->last_sign_in_at = Carbon::now();
$event->user->save();
}
}
Registering Events
Edit the EventServiceProvider included in our Laravel application to register the event listener.
app\Providers\EventServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
//Event For Login Details Data
'Illuminate\Auth\Events\Login' => [
'App\Listeners\UpdateLastSignInAt',
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
//
}
}
Update table structure
<?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->timestamp('last_sign_in_at')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Update Model
app\Models\User.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass as signable.
*
* @var array
*/
protected $fillable = [
'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',
];
protected $dates = [
'last_sign_in_at'
];
}
routes\web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TestLoginController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/user-login',[TestLoginController::class,'loginform'])->name('user.login');
Route::post('/check-login',[TestLoginController::class,'checklogin'])->name('post.login');
Route::get('/user-dashboard',[TestLoginController::class,'dashboard'])->name('user.dashboard');
app\Http\Controllers\TestLoginController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use\App\Models\User;
use Auth;
use Session;
use Illuminate\Support\Facades\Hash;
class TestLoginController extends Controller
{
public function loginform()
{
return view('login');
}
public function checklogin(Request $request)
{
$input = $request->all();
$this->validate($request, [
'email' => 'required',
'password' => 'required'],
[
'email.required' => 'Email is required',
'password.required' => 'Password is required']);
if(Auth::attempt(['email' => $input['email'], 'password' => $input['password']]))
{
Session::put('user_session', $input['email']);
return redirect('/user-dashboard');
}
else
{
return redirect('/user-login')->with('error','Invalid credentials');
}
}
public function dashboard()
{
return view('rememberme.dashboard');
}
}
Recomended article : Implement Remember me Functionality in Laravel 8.
resources\views\login.blade.php
<main>
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-6">
<div class="main">
<h3><a>Get Last Login Info of user in Laravel</a></h3>
@if(Session::has('flash_message_error'))
<div class="alert alert-sm alert-danger alert-block col-md-8 col-12 offset-4" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="close">
<span aria-hidden="true">× </span>
</button>
<strong>{!! session('flash_message_error')!!} </strong>
</div>
@endif
@if(Session::has('flash_message_success'))
<div class="alert alert-sm alert-success alert-block col-md-8 col-12 offset-4" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="close">
<span aria-hidden="true">× </span>
</button>
<strong>{!! session('flash_message_success')!!} </strong>
</div>
@endif
<form role="form" action="{{route('post.login')}}" method="post">
@csrf
<div class="form-group">
<label for="useremail">Email <span class="text-danger">*</span></label>
<input type="email" name="email" class="form-control">
@if ($errors->has('email'))
<span class="text-danger">{{ $errors->first('email') }}</span>
@endif
</div>
<div class="form-group">
<label for="userpassword">Password <span class="text-danger">*</span></label>
<input type="password" name="password" class="form-control">
@if ($errors->has('password'))
<span class="text-danger">{{ $errors->first('password') }}</span>
@endif
</div>
<button type="submit" class="btn btn btn-secondary">
Login
</button>
</form>
</div>
</div>
</div>
</div>
</main>
resources\views\dashboard.blade.php
<h1>Welcome , {{ Auth::user()->name }}</h1>
<h2>Last Sign In at : {{ Auth()->user()->last_sign_in_at->diffForHumans() }}</h2>
Run Application :
127.0.0.1:8000/user-login
In this article, we successfully integrated “How to Get users last login time in Laravel”, I hope this article will help you with your Laravel application Project.
Read also: How to use Traits in Laravel 8?