I'm trying to log all actions that users do (login / logout / CRUD) to a logs table in my database, and from what I've seen events look to be the right way to do this.
I've added a did($action) method to the User model, which logs an action to the database for the given user.
Here's what I've got so far:
EventServiceProvider.php
namespace App\Events;
use Illuminate\Support\ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->events->subscribe(new UserEventSubscriber);
}
}
UserEventSubscriber.php
namespace App\Events;
class UserEventSubscriber
{
public function login(\User $user)
{
return $user->did('logged_in');
}
public function logout(\User $user)
{
return $user->did('logged_out');
}
public function subscribe($events)
{
$events->listen('user.login', 'App\Events\UserEventSubscriber@login');
$events->listen('user.logout', 'App\Events\UserEventSubscriber@logout');
}
}
To log an action:
Event::fire('user.logout', array(Auth::user()));
I'm still trying to wrap my mind around service providers, so I could be very off-base here.
My questions:
1) Is a service provider the right thing to use or this?
2) Is there a better approach that doesn't require manually passing Auth::user() to the event every time?
3) At what level should events be fired? I'm leaning towards model whenever possible, as it would provide more useful logs from bulk actions. Otherwise there's the controller or repository.
4) These events are only necessary in the admin area (/admin/*). Would it be beneficial to somehow restrict this to only that section of the site?
5) My searches regarding the logging of user actions have been very unfruitful. Is this just something developers don't do? If so, what do they do?