Laravel Auth Jobs Development
Use this skill when a queued job must access the authenticated user that dispatched it. This package captures the authenticated user ID and guard during the HTTP request and restores that auth state inside queued jobs.
Install and Publish Configuration
composer require mrpunyapal/laravel-auth-jobs
php artisan vendor:publish --tag="auth-jobs-config"
Required Workflow
- Dispatch the job from a request handled by one of the middleware groups listed in
config/auth-jobs.php. - Let the package's
AuthenticateJobsHTTP middleware store the authenticated user ID and guard in Laravel context for that request. - Add
new AuthenticateJobto the queued job'smiddleware()method so the auth state is restored beforehandle()runs. - Read
auth()->user()or run authorization checks insidehandle()after the middleware has restored the auth state. - If your application needs different context keys, replace
context_keyswith a custom class that implementsHasContextKeys, or bind the interface in a service provider.
The package service provider automatically pushes AuthenticateJobs onto the configured middleware groups during package boot, so you do not need to register that middleware manually when the config is correct.
Job Example
use App\Models\Example;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Gate;
use MrPunyapal\LaravelAuthJobs\Jobs\Middleware\AuthenticateJob;
class ExampleJob implements ShouldQueue
{
use Queueable;
public function middleware(): array
{
return [new AuthenticateJob];
}
public function handle(): void
{
$user = auth()->user();
if ($user === null) {
return;
}
Gate::authorize('view', Example::class);
}
}
Custom Context Keys
namespace App\Auth;
use MrPunyapal\LaravelAuthJobs\Contracts\HasContextKeys;
final class CustomContextKeys implements HasContextKeys
{
public static function authIdKey(): string
{
return 'my_app_auth_user_id';
}
public static function authGuardKey(): string
{
return 'my_app_auth_guard';
}
}
Point context_keys in config/auth-jobs.php to \App\Auth\CustomContextKeys::class, or bind HasContextKeys to your implementation in a service provider.
Troubleshooting
- If
auth()->user()isnullinside the job, confirm the dispatching request used a configured middleware group and the request was authenticated. - Confirm the job defines
middleware()and returnsAuthenticateJob. - If you replace context keys, verify the custom class implements
HasContextKeysand thecontext_keysconfig points to it. - Re-run
composer testafter changing middleware or context integration.
Source: MrPunyapal/laravel-auth-jobs — distributed by TomeVault.