Mikail
Mikail

Reputation: 465

Laravel 4 sending mail after returning data from controller

I have a function in my controller which saves messages from users, first it saves message into database than it sends email to that user's mail address and than it returns json response to the sender.

Problem: sometimes it takes too long for email to be sent, and the sender has to wait long time for the response, or sometimes email is not even sent (due to some smpt problems etc.) and it triggers an error, however I don't really care that much if email is sent or not, most important that message is saved to the database.

What I'm trying to achieve:

I want to save message to the database, ->

immediately after that send response to the sender, ->

and only after run Mail::send();

so run Mail::send() after controller returns json to the sender, so the sender will receive a positive response regardless of how Mail::send() performs

    $message = new MessageDB;
    $message->listing_id = e(Input::get('listing_id'));
    $message->user_id = $listing->User->id;
    $message->name = e(Input::get('name'));
    $message->mobile = e(Input::get('mobile'));
    $message->message = e(Input::get('message'));
    if ($message->save()) {

        Mail::send('emails.message', ['user' => 'Jon Doe','message' => $message], function($m) use($listing){
            $listing_agent = $listing->Agent;
            if ($listing->agent == null) {
                $mail_to = $listing->User->email;
                $name = '';
            }else{
                $mail_to = $listing->Agent->email;
                $name = $listing->Agent->first_name.' '.$listing->Agent->second_name;
            }
            $m->to($mail_to)->subject('new message from company.com');

        });

        return ['success' => 1, 'message' => 'messasge has been sent']; 

Upvotes: 1

Views: 1857

Answers (1)

Tushar Ugale
Tushar Ugale

Reputation: 61

You can use Mail Queueing functions of Laravel. Here's the Link

  1. Mail::queue('emails.welcome', $data, function($message) {});
    Queue mail for background Sending.
  2. Mail::later(5, 'emails.welcome', $data, function($message){});
    Define Seconds after which mail will be sent.

Upvotes: 2

Related Questions