harlekoy / laravel-user-lastlogin

Manage tool for user's recent login

Stars
0

Users last login

Latest Version on Packagist
Build Status
Quality Score
Total Downloads

This is where your description should go. Try and limit it to a paragraph or two. Consider adding a small example.

Installation

You can install the package via composer:

composer require harlekoy/laravel-user-lastlogin

Publish assets

php artisan vendor:publish --tag=lastlogin.config
php artisan vendor:publish --tag=lastlogin.migrations

Usage

$user = User::first();

// Get the list of user logins
$user->logins

// Mark a user as login
$user->logins()->create(['ip_address' => request()->id()]);

// Get the user last login
$user->lastLogin

Admin

You can access directly the list of user logins just go to /logins

Listen When User Login

Create first the login event

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class LoggedIn
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * @var \App\User
     */
    public $user;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($user)
    {
        $this->user = $user;
    }
}

Create the listener

<?php

namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class MarkAsLoggedIn
{
    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle($event)
    {
        $event->user->logins()
            ->create(['ip_address' => request()->ip()]);
    }
}

Update app/Providers/EventServiceProvider.php

 /**
  * The event listener mappings for the application.
  *
  * @var array
  */
 protected $listen = [
     Registered::class => [
         SendEmailVerificationNotification::class,
+        MarkAsLoggedIn::class,
     ],
+    LoggedIn::class => [
+        MarkAsLoggedIn::class,
+    ],
 ];

Add or update your authenticated method in app/Http/Controllers/Auth/LoginController.php file on your Laravel app

/**
 * The user has been authenticated.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  mixed  $user
 * @return mixed
 */
protected function authenticated(Request $request, $user)
{
    event(new LoggedIn($user));
}

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.