Laravel has a feature called Events that allows us to fire an event and listen to it through the Listeners. To implement this feature, we will listen to the login event and save the login date to know how much of the last time a user has been logged in.
I have based on this article.
First of all, we have to add the field to the database. So, we have to create a migration:
1 |
php artisan make:migration add_last_login_to_users_table |
Add this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddLastLoginToUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function(Blueprint $table) { $table->timestamp('last_login'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function(Blueprint $table) { $table->dropColumn('last_login'); }); } } |
Execute the migrations:
1 |
php artisan migrate |
Now, we have to register the event and its listener. Open EventServiceProvider.php and add this code to the $listen array:
1 2 3 4 5 |
protected $listen = [ 'Illuminate\Auth\Events\Login' => [ 'App\Listeners\LastLogin', ], ]; |
Once this is done, execute the following command, which will create both the events and listeners in the array.
1 |
php artisan event:generate |
The event won’t be created because is native to Laravel, but the listener yes, it will be created. We can find it in app/Listeners :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<?php namespace App\Listeners; use Illuminate\Auth\Events\Login; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Carbon\Carbon; class LastLogin { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param Login $event * @return void */ public function handle(Login $event) { $user = $event->user; $user->last_login = Carbon::now(); $user->save(); } } |
The handle function accesses the user sent from the event (Login), adds the last login date (which will be now) to the object and saves it to the database.
To display the value in the view, just put this:
1 |
{{ $user->last_login }} |
If you want to format it, we can do it like this:
1 |
{{ $user->last_login->diffForHumans() }} |
And will have to add to the model User.php this:
1 2 3 |
protected $dates = [ 'last_login' ]; |
In this post we have only created a listener (LastLogin) since the event we use (Login) is native to Laravel, if you want to see how a custom event is created you can do it in the Laravel documentation, it is very simple
-
– https://laravel.com/docs/5.4/events
– http://paulcracknell.com/79/laravel-event-handler-last-login/