Skip to content

Commit 4a389ce

Browse files
authored
Merge pull request #141 from ModulesSoft/auth-events
Update auth and add custom authentication events with considering Laravel version 11
2 parents d21f7ad + 98daa2f commit 4a389ce

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

auth.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
- [Did you know about Auth::once()?](#did-you-know-about-authonce)
99
- [Change API Token on users password update](#change-api-token-on-users-password-update)
1010
- [Override Permissions for Super Admin](#override-permissions-for-super-admin)
11+
- [Custom Authentication Events](#custom-authentication-events)
1112

1213
### Check Multiple Permissions at Once
1314

@@ -117,3 +118,55 @@ Gate::before(function (?User $user, $ability) {
117118
});
118119
```
119120

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

Comments
 (0)