Laravel's authentication system fires various events during the authentication process, allowing you to hook into these events and perform additional actions or custom logic.
For example, you might want to log users Login.
You can achieve this by listening to the Illuminate\Auth\Events\Login
event.
To implement it:
Step 1. Create event listener classes for the events. You can generate these classes using Artisan command:
php artisan make:listener LogSuccessfulLogin
Step 2. Write the logic to execute when the events occur:
// app/Listeners/LogSuccessfulLogin.phpnamespace App\Listeners; use Illuminate\Support\Facades\Log;use Illuminate\Auth\Events\Login; class LogSuccessfulLogin{ public function handle(Login $event) { // Log the successful login Log::info("User with ID ".$event->user->id." successfully logged in."); }}
For Laravel version 10.x or older, you need to register the newly created event listener manually:
Step 3. Register your event listeners in the EventServiceProvider
:
// app/Providers/EventServiceProvider.phpnamespace App\Providers; use Illuminate\Auth\Events\Login;use App\Listeners\LogSuccessfulLogin; class EventServiceProvider extends ServiceProvider{ protected $listen = [ Login::class => [ LogSuccessfulLogin::class, ] ]; // Other event listeners...}
Now, whenever a user logs in to your application, you can noticed it by checking the Laravel log file at /storage/logs/laravel.log
.