66use Illuminate \Auth \Events \Authenticated ;
77use Illuminate \Console \Events \CommandFinished ;
88use Illuminate \Console \Events \CommandStarting ;
9+ use Illuminate \Contracts \Auth \Authenticatable ;
910use Illuminate \Contracts \Container \BindingResolutionException ;
1011use Illuminate \Contracts \Container \Container ;
1112use Illuminate \Contracts \Events \Dispatcher ;
13+ use Illuminate \Database \Eloquent \Model ;
1214use Illuminate \Database \Events \QueryExecuted ;
1315use Illuminate \Http \Request ;
1416use Illuminate \Log \Events \MessageLogged ;
@@ -421,9 +423,7 @@ private function addLogBreadcrumb(string $level, ?string $message, array $contex
421423 */
422424 protected function authenticatedHandler (Authenticated $ event )
423425 {
424- $ this ->configureUserScopeWithRequest ([
425- 'id ' => $ event ->user ->getAuthIdentifier (),
426- ]);
426+ $ this ->configureUserScopeFromModel ($ event ->user );
427427 }
428428
429429 /**
@@ -433,20 +433,31 @@ protected function authenticatedHandler(Authenticated $event)
433433 */
434434 protected function sanctumTokenAuthenticatedHandler (Sanctum \TokenAuthenticated $ event )
435435 {
436- $ this ->configureUserScopeWithRequest ([
437- 'id ' => $ event ->token ->tokenable ->getAuthIdentifier (),
438- ]);
436+ $ this ->configureUserScopeFromModel ($ event ->token ->tokenable );
439437 }
440438
441439 /**
442440 * Configures the user scope with the user data and values from the HTTP request.
443441 *
444- * @param array $userData
442+ * @param mixed $authUser
445443 *
446444 * @return void
447445 */
448- private function configureUserScopeWithRequest ( array $ userData ): void
446+ private function configureUserScopeFromModel ( $ authUser ): void
449447 {
448+ $ userData = [];
449+
450+ // If the user is a Laravel Eloquent model we try to extract some common fields from it
451+ if ($ authUser instanceof Model) {
452+ $ userData = [
453+ 'id ' => $ authUser instanceof Authenticatable
454+ ? $ authUser ->getAuthIdentifier ()
455+ : $ authUser ->getKey (),
456+ 'email ' => $ authUser ->getAttribute ('email ' ) ?? $ authUser ->getAttribute ('mail ' ),
457+ 'username ' => $ authUser ->getAttribute ('username ' ),
458+ ];
459+ }
460+
450461 try {
451462 /** @var \Illuminate\Http\Request $request */
452463 $ request = $ this ->container ->make ('request ' );
@@ -463,7 +474,7 @@ private function configureUserScopeWithRequest(array $userData): void
463474 }
464475
465476 Integration::configureScope (static function (Scope $ scope ) use ($ userData ): void {
466- $ scope ->setUser ($ userData );
477+ $ scope ->setUser (array_filter ( $ userData) );
467478 });
468479 }
469480
0 commit comments