Laravel trigger event after return response

all.
I’m new to stackoverflow and laravel.
Currently I’m working on laravel application which is simple ecommerce. all functionalities completed.
currently I’m facing small issue, which is when placing an order it takes some much time to return success.
I figured out that issue from Email notifications. I’ve 3 email to send when order created (New order to admin & customer , stock update to admin). this event i added before return redirect to success page, so success page only shows when these events are completed.

My Final point is:
how to trigger this event after return success, or any other method to trigger an event?

public function createOrder(){
$order=new Order;
$order->comment="";
$order->payment_method=$request->payment_method;
$order->payment_status="unpaid";
$order->order_method=$request->order_method;
$order->client_name=$request->billing_first_name;
$order->client_last_name=$request->billing_last_name;
$order->client_email=$request->billing_email;
$order->phone=$request->billing_phone;
$order->order_price=0;
$order->save();

    event(new OrderCreated($this->order->id)); here i'm triggering event. event triggeing properly and emails working properly.
    
    return redirect()->route('order.success', ['order' => $this->order]);

}

  • use Jobs for deploying your email so you can process it separately without blocking the main request, check the queue docs

    – 

To avoid delaying the response due to the processing of email notifications, you can queue these tasks to run in the background.

ENV:

QUEUE_CONNECTION=database

ARTISAN:

php artisan queue:table
php artisan migrate

Queue the OrderCreated Event Listener:

use Illuminate\Contracts\Queue\ShouldQueue;

class SendOrderConfirmation implements ShouldQueue
{
    // listener logic
}

Dispatch the creaetOrder Event:

public function createOrder() {
    // your existing code

    event(new OrderCreated($this->order->id));
    
    return redirect()->route('order.success', ['order' => $this->order]);
}

Run the Queue:

php artisan queue:work

Leave a Comment