datpmwork / laravel-auth-queue
Preserve the authenticated user context when dispatching Laravel queued jobs.
Fund package maintenance!
datpmwork
Requires
- php: ^7.4|^8.0
- illuminate/support: ^9.0|^10.0|^11.0|^12.0
Requires (Dev)
- ext-json: *
- larastan/larastan: ^1.0|^2.9|^3.1
- laravel/pint: ^1.0
- nunomaduro/collision: ^6.0|^7.0|^8.0
- orchestra/testbench: ^7.0|^8.0|^9.0|^10.0
- pestphp/pest: ^1.0|^2.0|^3.0
- pestphp/pest-plugin-laravel: ^1.0|^2.0|^3.0
- phpstan/extension-installer: ^1.3
- phpstan/phpstan-deprecation-rules: ^1.1|^2.0
- phpstan/phpstan-phpunit: ^1.3|^2.0
README
This package preserves the authenticated user context when dispatching Laravel queued jobs, notifications, or event listeners.
It allows you to seamlessly access the authenticated user who originally dispatched the job through Laravel's auth() manager when the job is being handled.
This is particularly useful when you need to maintain user context across asynchronous operations.
Requirements
- PHP ^7.4 | > 8.0
- Laravel 9.x | 10.x | 11.x | 12.x
Support us
You can support this project via GitHub Sponsors.
Installation
You can install the package via composer:
composer require datpmwork/laravel-auth-queue
Usage
Add WasAuthenticated
trait to any Job
, Notification
, Listener
which need to access auth
data when the Job was dispatched
Example Job
class SampleJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, WasAuthenticated; public function handle() { # auth()->user() was the authenticated user who dispatched this job logger()->info('Auth ID: '. auth()->id()); } }
Example Notification
class SampleNotification extends Notification implements ShouldQueue { use Queueable, WasAuthenticated; public function via(): array { return ['database']; } public function toDatabase(): array { # auth()->user() was the authenticated user who triggered this notification return [auth()->id()]; } }
Example Subscriber
class SampleSubscriber implements ShouldQueue { use Queueable, WasAuthenticated; public function subscribe(Dispatcher $dispatcher) { $dispatcher->listen('eloquent.updated: ' . User::class, [self::class, 'onUserUpdated']); } public function onUserUpdated(User $user) { # auth()->user() was the authenticated user who triggered this event logger()->info('Auth ID: '. auth()->id()); } }
Testing
./vendor/bin/pest
Changelog
Please see CHANGELOG for more information on what has changed recently.
Credits
License
The MIT License (MIT). Please see License File for more information.