login event handling in laravel 5
EDIT: this only works in 5.0.* and 5.1.*.
For the 5.2.* solution see JuLiAnc response below.
after working with both proposed answers, and some more research i finally figured out how to do this the way i was trying at first.
i ran the following artisan command
$ php artisan handler:event AuthLoginEventHandler
Then i altered the generated class removing the import of the Event class and and imported the user model. I also passed User $user
and $remember
to the handle method since when the auth.login event is fired, thats what is passed.<?php namespace App\Handlers\Events;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldBeQueued;
use App\User;
class AuthLoginEventHandler {
/**
* Create the event handler.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param User $user
* @param $remember
* @return void
*/
public function handle(User $user, $remember)
{
dd("login fired and handled by class with User instance and remember variable");
}
}
now i opened EventServiceProvided.php and modified the $listen
array as follows:protected $listen = [
'auth.login' => [
'App\Handlers\Events\AuthLoginEventHandler',
],
];
i realized if this doesn't work at first, you may need to$ php artisan clear-compiled
There we go! we can now respond to the user logging in via the auth.login event using an event handler class! Laravel 5.2 Login Event Handling
You are almost there, just a few changes more, Events and Listeners for authentication have changed a little in Laravel 5.2:
the handle method in UpdateLastLoginOnLogin should have just an event as parameter
namespace App\Listeners;
use Carbon\Carbon;
use Auth;
class UpdateLastLoginOnLogin
{
public function handle($event)
{
$user = Auth::user();
$user->last_login_at = Carbon::now();
$user->save();
}
}
And for the EventServiceProvider you specify the listeners like this :protected $listen = [
'Illuminate\Auth\Events\Login' => [
'App\Listeners\UpdateLastLoginOnLogin@handle',
],
];
Laravel 5.2 : Login attempt Event Handling
According to documentation you are right that Auth::user()
object is only created when user is authenticated.
Laravel 5.4 listener to save users login
I think you should try to get the user directly from the event.
Something like that :
namespace App\Listeners;
use Illuminate\Auth\Events\Login;
use Illuminate\Http\Request;
class LogSuccessfulLogin
{
/**
* Create the event listener.
*
* @param Request $request
* @return void
*/
public function __construct(Request $request)
{
$this->request = $request;
}
/**
* Handle the event.
*
* @param Login $event
* @return void
*/
public function handle(Login $event)
{
$user = $event->user;
$user->last_login_at = date('Y-m-d H:i:s');
$user->last_login_ip = $this->request->ip();
$user->save();
}
}
This is a good tutorial about that :https://stevenwestmoreland.com/2017/03/recording-last-login-information-using-laravel-events.html
Hope this helps you
How to handle a Login event for a specific auth guard?
You can check in your listener if the user is logged via that specific guard. If true, do your normal stuff.
if(Auth::guard('web')->check()){
// Do normal stuff
}else {
// If you want an else.
}
How to test laravel login event
The following sets the namespace with the class name included. Does not create an event object, as the error states that needs to be passed.
$event = \Illuminate\Auth\Events\Login::class;
You need to instantiate an Login event, the first parameter is the guard, use the one you have in your config, second parameter is user and third is if it should be remembered as a bool
.use Illuminate\Auth\Events\Login;
$event = new Login('web', $this->user, true);
Which will fix your current error and most likely as i see it fix the test.I would thou believe you do not need to login your user for this test to work. So remove the login code
Auth::login($this->user);
Event listener in laravel 5.4
Here is how I achieved it.
I created a new Listenener here App/Listeners/LogSuccessfullLogin.php
namespace App\Listeners;
use Illuminate\Auth\Events\Login;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use \Carbon\Carbon;
class LogSuccessfulLogin
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param Login $event
* @return void
*/
public function handle(Login $event)
{
$event->user->last_login = Carbon::now();
$event->user->save();
}
}
and then in the EventServiceProvider
, I observed for the Illuminate\Auth\Events\Login
event as such:<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'Illuminate\Auth\Events\Login' => [
'App\Listeners\LogSuccessfulLogin',
]
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();
//
}
}
So each time a user is logging in, it will save the timestamp in the last_login
field in the users
table. Hope this helps!
Related Topics
How to Make an Array of Times with Half Hour Intervals
Php-Font-Lib Must Either Be Installed via Composer or Copied to Lib/Php-Font-Lib
Convert Multidimensional Objects to Array
How to Put Double Quotes Inside a String Within an Ajax JSON Response from PHP
In Magento 1.9.0.0 How to Enable Template Path Hint
Get Folders with PHP Glob - Unlimited Levels Deep
How to Sort an Array by Similarity in Relation to an Inputted Word
Find Windows 32 or 64 Bit Using PHP
Str_Replace() for Multiple Value Replacement
How to JSON_Encode Array with French Accents
Mail Not Sending with PHPmailer Over Ssl Using Smtp
Ssl Alternative - Encrypt Password with JavaScript Submit to PHP to Decrypt
PHP Pdo Bindparam Was Falling in a Foreach
Laravel 4 - Including a "Partial" View Within a View (Without Using Blade Template)