简体   繁体   中英

Laravel add multiple Jobs at a time

For a user action, I need to send email to all of his subscribers. In this case, the emails should be queued to send later.

I used jobs for that, which can accept single user instance at a time (followed Laravel Doc ) and it inserts a job in job table. This is fine.

Now, as the subscribers number is more that one, how can I add multiple user instance or jobs at a time in the jobs table? In Laravel 5.2, how can I achieve that?

I'm not sure if i'm missing something here by reading your question, but if you are implementing your own job queue, couldnt you just change the constructor to accept an collection (array) of users instead and in the handle method simply run a foreach which would email them?

Example in Laravel docs modified to accept a collection of users instead of single user:

<?php


namespace App\Jobs;

use App\User;
use App\Jobs\Job;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

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

protected $users = [];

/**
 * Create a new job instance.
 *
 * @param  User  $user
 * @return void
 */
public function __construct($users) //Pass in an array of your user objects
{
    $this->users = $users;
}

/**
 * Execute the job.
 *
 * @param  Mailer  $mailer
 * @return void
 */
public function handle(Mailer $mailer)
{
  foreach($users as $currentUser){
      $mailer->send('emails.reminder', ['user' => $currentUser], function ($){
        //code here
    });

    $currentUser->reminders()->create(...);
   }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM