Search code examples
laravelqueuejobs

Laravel 7- How to pass data(variable) from CONTROLLER to JOB to MAIL to VIEW?


I have seen this question asked a few times without anyone really answering it, or their method did not work. I am going to paste what I have thus far but I am still getting an error that the variable could not be found. The job queue works just fine but can not find the variable in the view. Below the code are the other resources that I have viewed that did not work.

ERROR MESSAGE- ErrorException: Undefined variable: newNeed in /Users/JandB/Desktop/myProject/storage/framework/views/dab250ddee8692f8f6a1fa3334aad4ba0eb81350.php:1

CONTROLLER

public function store(StoreNeedRequest $request)
{
    $users = User::where('team_id', '=', auth()->user()->team_id)->get();

    $newNeed = 4;

    foreach ($users as $user) { 
        SendNeedsEmailJob::dispatch($newNeed, $user);

        }

}

JOB

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

    public $newNeed;
    protected $user;
    
 
    public function __construct($newNeed, $user)
    {
        $this->newNeed = $newNeed;
        $this->user = $user; 
    }

   
    public function handle()
    {
     
    Mail::to($this->user->email)
      ->send(new NeedsMail($this->newNeed));
        
            
    }
}

MAIL

class NeedsMail extends Mailable
{
    use Queueable, SerializesModels;
    public $newNeed;
   
 
    public function __construct($newNeed)
    {
        $this->newNeed = $newNeed;
        
    } 

   
    public function build()
    {
     
        return $this->markdown('emails.needs')->with('newNeed', $this->newNeed)->subject('New NEED');
    }
}

VIEW

{{$newNeed}}

Other Resources

https://laracasts.com/discuss/channels/laravel/laravel-job-not-passing-variable-to-end-view https://medium.com/@petehouston/passing-data-to-blade-template-from-queue-in-laravel-79130c598f01 Laravel queues issues when I pass data from controller to jobs


Solution

  • Make sure you have removed any previous jobs, and cleared any caching so that you aren't running an older version of NeedsMail without the $newNeed variable defined.