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.

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 68 courses (1188 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses