Search code examples
phplaravellaravel-4laravel-5jobs

Change value of parameters inside Laravel Job Class


I'm trying to send an email with a job class in Laravel, the point is I need to keep track of the notificactions sent by mail. I have a table named "Notifications" wich has the columns status and lastUpdated (these are the one regarding this issue).

In order to update the row of the Notifications table I need to know the ID of that row. I'm trying to change the value of a parameter which is a model being sent as parameter, inside a job class. This model is a "Notifications"

My question here is, do the parameters inside a job class persist to the next call once they've been changed from inside the class? Apparently is not working that way. If this is not possible, can someone suggest any workaround?

class SendReminderEmail extends Job implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    public function __construct($lastNotification)
    {
        $this->lastNotification = $lastNotification;
    }       

    //NULL means it's the first time the job has been called
    protected $lastNotification;

    public function handle(Mailer $mailer)
    {

        $mailer->send('user.welcome', ['username' => 'Luis Manuel'], function($message)
        {
            $message->from('[email protected]', 'Luis');
            $message->to('[email protected]', '[email protected]');     
            $message->subject('Subject here!');            
        });   

        if(count($mailer->failures()) > 0)  
        {
            if($this->lastNotification == null)
            {
                $this->lastNotification = new Notification;

                $this->lastNotification->status  = false;
                $this->lastNotification->lastUpdated  = Carbon::now();
            }   
            else
            {
                $this->lastNotification->status  = false;
                $this->lastNotification->lastUpdated = Carbon::now();
            }

            $this->lastUpdated->save();
        }       

    }
}

Solution

  • How I solved it:

    Before dispatching the job inside a controller I created the Notification model, saved it an then passed it to the job class as parameter.

        public function ActionSomeController()
        {
            $notification = new Notifiaction;
            $notification->save();
    
            $newJob = (new SendReminderEmail($notification));
            $this->dispatch($newJob);
        }
    

    And in the Job Class :

        public function __construct($notification)
        {
            $this->notification = notification;
        }
    
        public function handler(Mailer $mailer)
        {
            /*
            *   Some extra code abover here 
            */
    
            $this->notification->lastUpdated = Carbon::now();
        }
    

    And it works like a charm!