sqits / laravel-userstamps

Package to maintain the users who created, updated and deleted eloquent models
MIT License
18 stars 7 forks source link

Not working in queue #19

Closed edikurniawan-dev closed 8 months ago

edikurniawan-dev commented 8 months ago

I have a job to sent email to all users, after process sent email done, i update the data, but why column updated_by be null?

// app/Jobs/ProcessSendEmail.php

class ProcessSendEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     */
    public function __construct(protected Payroll $payroll)
    {
        //
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        try {
            Mail::to($payroll->email)->send(new PayrollEmail($payroll, true));

            Payroll::find($this->payroll->id)->update([
                'sent_at' => Carbon::now(),
            ]);
        } catch (\Exception $e) {
        }
    }
}
alexmayo commented 8 months ago

Does the Payroll model use the HasUserStamps trait? See the below example.

use Sqits\UserStamps\Concerns\HasUserStamps;

class Payroll extends Model {

    use HasUserStamps;

    //...

}
edikurniawan-dev commented 8 months ago

Yes, Payroll model use the HasUserStamps trait.

This code work fine if in controller, but if in jobs updated_by to be null

Mail::to($payroll->email)->send(new PayrollEmail($payroll, true));

Payroll::find($this->payroll->id)->update([
      'sent_at' => Carbon::now(),
]);
alexmayo commented 8 months ago

You should pass the userId to the job, and then utilise Auth::loginUsingId to authenticate inside the job. Otherwise, the job (and userstamps) has no idea who the current user is, which sets the updated_by to null.

// app/Jobs/ProcessSendEmail.php

class ProcessSendEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     */
    public function __construct(protected Payroll $payroll, protected  $userId)
    {
        //
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        if(Auth::loginUsingId($this->userId)) {
            try {
                Mail::to($this->payroll->email)->send(new PayrollEmail($this->payroll, true));

                Payroll::find($this->payroll->id)->update([
                    'sent_at' => Carbon::now(),
                ]);
            } catch (\Exception $e) {
            }
        }
    }
}

Then, when queueing the job, ensure you pass the current user ID to the new job.

new ProcessSendEmail($payroll, $user->id);
edikurniawan-dev commented 8 months ago

Ahh I see, thanks for that solution