Execute more than one event one after another before rendering something in Laravel | Events | Listeners

625 Views Asked by At

I have a Laravel application where I use Laravel event and Listeners. In my real use case, whenever a user visits the Invoice details page I want to execute two events. One of them actually inserts some related data for the invoice.

but on the display page, that data is not showing(which was inserted by events) however data is inserted into the table successfully

/**
 * Display the specified resource.
 *
 * @param  \App\Invoice  $invoice
 * @return \Illuminate\Http\Response
 */
public function show(Invoice $invoice)
{
    event(new EventA($invoice->user));
    event(new EventB($invoice));
    return view('invoices.'.$invoice->type.'.show', compact('invoice'));
}

What I want is to execute these two events and wait until they complete their job and then render the details page.

It will be better if someone helps me know how we can return data from the event execute statements like

eventAExecuted = event(new EventA($invoice->user)); // expect true
eventBExecuted = event(new EventB($invoice)); // expect true

so then I can perform the boolean expression on these

if (eventAExecuted && eventBExecuted) {
    return view('invoices.'.$invoice->type.'.show', compact('invoice'));
}

UPDATED

I return true from the Listeners which return the following output

Array ( [0] => 1 [1] => 1 ) Array ( [0] => 1 )

So I apply boolean expression but the data which I inserted through listeners is inserted into the table but does not print in the controller at the first time.

eventAExecuted = event(new EventA($invoice->user)); // expect true and insert hasMany realtion data. for eg., invoice->transactions
eventBExecuted = event(new EventB($invoice)); // expect true

if ($eventAExecuted && $eventBExecuted) {
    print_r($invoice->transactions); // getting empty collection however data is inserted successfully.
    die;
    return view('invoices.'.$invoice->type.'.show', compact('invoice'));
}
0

There are 0 best solutions below