It sounds like the issue you're encountering is due to the fact that the queued jobs are sometimes retaining the authentication state from the time they were queued, which can lead to unexpected behavior when auth()->user() is called within the job.
To ensure that auth()->user() returns null in queued jobs, you can explicitly set the user to null at the beginning of the job. This will prevent any residual authentication state from affecting your logs.
Here's a possible solution:
-
Clear the authentication state at the beginning of the job:
Modify your job class to clear the authentication state before performing any actions. This can be done by setting the authenticated user to
null.use Illuminate\Support\Facades\Auth; class YourJobClass implements ShouldQueue { public function handle() { // Clear the authentication state Auth::setUser(null); // Your job logic here $order->log('log_key', 'log_message'); } } -
Ensure the
logmethod handles thenulluser correctly:Your
logmethod already handles the case whereauth()->user()isnullby assigning theCustodian::find(Custodian::NAMES['System'])user. This part of your code seems correct, so no changes are needed here.public function log($key, $log, Model $updater = null): void { if (is_null($updater) && auth()->user()) { $updater = auth()->user(); } if (is_null($updater) && !auth()->user()) { $updater = Custodian::find(Custodian::NAMES['System']); } $this->changelog()->create([ 'log_key' => $key, 'log_value' => $log, 'updater_id' => $updater?->id, 'updater_type' => (!is_null($updater)) ? get_class($updater) : NULL, ]); }
By explicitly setting the authenticated user to null at the beginning of your queued job, you can ensure that auth()->user() will return null and your log method will correctly assign the "System" user as the updater.
This should resolve the issue of random users being assigned as the updater in your logs.