skip to Main Content

I’m dispatching a delayed job that should created some entries in the database:

`$userId = Auth::user() ? Auth::user()->getAuthIdentifier() : null;
 $job = new DelayedAddPeopleJob($event, $userId);
 dispatch($job)->delay(DelayedAddPeopleJob::DELAY);`

After 15 minutes DelayedAddPeopleJob is executed and in there im creating entries in the DB if they do not exist.

`AutoAddHistory::firstOrCreate([
                AutoAddHistory::MATRIX_ID_COLUMN => $matrixId,
                AutoAddHistory::ROLE_ID_COLUMN => $ppr->getRoleId(),
                AutoAddHistory::PERSON_ID_COLUMN => $ppr->getPersonId(),
                AutoAddHistory::CREATED_BY_COLUMN => $this->placedBy,
 ]);`

In this instance the placedBy is the userId passed to DelayedAddPeopleJob. However when the entries appear in the database after those 15 minutes the CREATED_BY is NULL in the database for some reason.

Am I doing something wrong? I tried to find a solution or similar problem but can’t. Tried accessing it via magic method instead on const and it did not help.

2

Answers


  1. Chosen as BEST ANSWER

    I tried one solution that seems to worked. The code that specifies $userId works properly. The issue was model events that happened when saving the model after the 15 minutes delay. Inside the UserStamps trait

     if (is_null($model->{$createByColumn}) && !empty($createByColumn)) {
            $model->{$createByColumn} = $auth->getAuthIdentifier();
        }
    

    $auth->getAuthIdentifier() was returning null on model event after delay and it overwrites the placedBy attribute. I solved it by:

      $autoAddHistory = AutoAddHistory::firstOrNew([
                    AutoAddHistory::MATRIX_ID_COLUMN => $matrixId,
                    AutoAddHistory::ROLE_ID_COLUMN => $ppr->getRoleId(),
                    AutoAddHistory::PERSON_ID_COLUMN => $ppr->getPersonId(),
                    AutoAddHistory::CREATED_BY_COLUMN => $this->placedBy,
                ]);
                $autoAddHistory->setAuth($authUser);
                $autoAddHistory->save();
    

    Where the $authUser = new NullUser(['id' => $this->placedBy]); This solved the problem and entries. Rather than using firstOrUpdate I used firstOrNew and adjusted the system auth user and saved the model manually.


  2. Job can’t contain a user session data.

    For this reason, your condition $userId = Auth::user() ? Auth::user()->getAuthIdentifier() : null; always goes to false and return null, you have to call the userId in another way.

    You can store the userID at the parent record table and fetch from here once you need.

    Also make sure CREATED_BY column fillable difined at your model.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search