|
8 | 8 | - [Did you know about Auth::once()?](#did-you-know-about-authonce)
|
9 | 9 | - [Change API Token on users password update](#change-api-token-on-users-password-update)
|
10 | 10 | - [Override Permissions for Super Admin](#override-permissions-for-super-admin)
|
| 11 | +- [Custom Authentication Events](#custom-authentication-events) |
11 | 12 |
|
12 | 13 | ### Check Multiple Permissions at Once
|
13 | 14 |
|
@@ -117,3 +118,55 @@ Gate::before(function (?User $user, $ability) {
|
117 | 118 | });
|
118 | 119 | ```
|
119 | 120 |
|
| 121 | +### Custom Authentication Events |
| 122 | + |
| 123 | +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. |
| 124 | + |
| 125 | +For example, you might want to log users Login. |
| 126 | +You can achieve this by listening to the `Illuminate\Auth\Events\Login` event. |
| 127 | + |
| 128 | +To implement it: |
| 129 | +1. Create event listener classes for the events. You can generate these classes using Artisan commands: |
| 130 | +```bash |
| 131 | +php artisan make:listener LogSuccessfulLogin |
| 132 | +``` |
| 133 | +2. Write the logic to execute when the events occur: |
| 134 | +```php |
| 135 | +// app/Listeners/LogSuccessfulLogin.php |
| 136 | +namespace App\Listeners; |
| 137 | + |
| 138 | +use Illuminate\Support\Facades\Log; |
| 139 | +use Illuminate\Auth\Events\Login; |
| 140 | + |
| 141 | +class LogSuccessfulLogin |
| 142 | +{ |
| 143 | + public function handle(Login $event) |
| 144 | + { |
| 145 | + // Log the successful login |
| 146 | + Log::info("User with ID ".$event->user->id." successfully logged in."); |
| 147 | + } |
| 148 | +} |
| 149 | +``` |
| 150 | + |
| 151 | +For Laravel version 10.x or older, you need to register the newly created event listener manually: |
| 152 | + |
| 153 | +3. Register your event listeners in the `EventServiceProvider`: |
| 154 | +```php |
| 155 | +// app/Providers/EventServiceProvider.php |
| 156 | +namespace App\Providers; |
| 157 | + |
| 158 | +use Illuminate\Auth\Events\Login; |
| 159 | +use App\Listeners\LogSuccessfulLogin; |
| 160 | + |
| 161 | +class EventServiceProvider extends ServiceProvider |
| 162 | +{ |
| 163 | + protected $listen = [ |
| 164 | + Login::class => [ |
| 165 | + LogSuccessfulLogin::class, |
| 166 | + ] |
| 167 | + ]; |
| 168 | + |
| 169 | + // Other event listeners... |
| 170 | +} |
| 171 | +``` |
| 172 | +Now, whenever a user logs in to your application, you can get noticed by checking the Laravel log file at `/storage/logs/laravel.log`. |
0 commit comments