Search code examples
laravellaravel-5.3laravel-5.4

Send email in background : Laravel 5.4


I am using an inbuilt code in Laravel to send Email Notification. Code is below. I am using smtp to send email

class RegisterNotification extends Notification
{
    use Queueable;

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

    public function via($notifiable)
    {
        return ['mail'];
    }

    public function toMail($notifiable)
    {
        return (new MailMessage)
                ->line('hi');
    }

    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

Here the problem is, it takes around 5 seconds to complete the process and control does not come back. I am assuming that if it come back and do the email sending work in background...it would save a lot of time.

Is there any inbuilt work to do the same? I meant, control should come back and should say email sent...and then it should do the work in background.

Email Sending code in Controller

class apiRegisterController extends Controller
{
    public function Register(RegisterRequest $request) {

        $RegisterNotification = new RegisterNotification($Token);
        $User->notify($RegisterNotification);
    }
}

Code for Queue

Controller Code

$job = (new SendForgotPasswordEmail($Data))->onConnection('database');
dispatch($job);

Job

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

    protected $Data;

    public $tries = 5;

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

    public function handle()
    {
        $Token = $this->Data["Token"];
        $User = $this->Data["User"];
        $RegisterNotification = new RegisterNotification($Token);
        $User->notify($RegisterNotification);
    }
}

Solution

  • Step 1: Change class RegisterNotification extends Notification to class RegisterNotification extends Notification implements ShouldQueue

    Step 2: Implement a queue driver. In your config/queue.php make sure your driver is not set to sync like so: 'default' => env('QUEUE_DRIVER', 'sync'), and make sure your .env doesnt have QUEUE_DRIVER=sync. You can look at the Laravel documentation for queues to choose an appropriate queue driver