Skip to main content
Quick Tip

Custom Authentication Events

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.php
namespace 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.php
namespace 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.

Enjoyed This Tip?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.