What would be the best way to log user login / logout / attempt activity? Thanks for another great package!
For most cases, I'd suggest simply manually calling the activity() function in your controllers where the actions are happening.
Another strategy would be to have your application emit events for login/logout/etc., and setting up a listener to log the actions.
There's not really a generic way-to-go here I think, it depends on your application.
Thanks - I think for the use case of logging Laravel out of the box login specifically, the event approach must be used as the action happens in the framework source as opposed to the Auth controller. Is that correct?
What I did, simply create an Event & a Listener.
Here my LogEvent
<?php
namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class LogEvent extends Event
{
use SerializesModels;
public $subject;
public $description;
public $user;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($user, $subject, $description)
{
$this->user = $user;
$this->subject = $subject;
$this->description = $description;
}
/**
* Get the channels the event should be broadcast on.
*
* @return array
*/
public function broadcastOn()
{
return [];
}
}
And for my LogEvent listener:
<?php
namespace App\Listeners;
use App\Events\LogEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Spatie\Activitylog\Models\Activity;
class LogEvent
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param LogEvent $event
* @return void
*/
public function handle(LogEvent $event)
{
activity($event->subject)
->by($event->user)
->log($event->description);
}
}
So, later on I just call event(new \App\Events\LogEvent(Auth::user(), 'Authentication', 'Successfully logged in.')); to start logging.
Thanks for posting your approach @cleanique-coders
Here's how we do it for our own projects: https://github.com/spatie-custom/blender/blob/master/app/Http/Controllers/Back/AuthController.php#L31
Thanks for the suggestions. I didn't realize that Laravel broadcasts events for login activity. So with that known, I ended creating a listener for the Login event and called activity()->log('Login successful'); in the handle method of that listener.
Most helpful comment
Thanks for the suggestions. I didn't realize that Laravel broadcasts events for login activity. So with that known, I ended creating a listener for the Login event and called
activity()->log('Login successful');in the handle method of that listener.