Manually Triggering Events in Laravel

I recently came across a situation where I had to change the business logic and to notify a user who was added in the new logic and... it was In the Production!!! So after some research I found that it is possible, by using Tinker and laravel Event methods.

How to do?

Let's say we have a collection called $transactions and we want to manually trigger an event for a specific transaction. We can use php artisan tinker to achieve this.

NB: Make sure you take the DB backup before and do this firefighting on a non-busy day, or after putting the application in Maintenance mode.

1. Open Tinker

First, open Tinker by running the following command in your terminal:

php artisan tinker

2. Find the Appropriate Transaction

Use Tinker to find the transaction you want to trigger the event for. For example:

$transaction = \App\Models\Transaction::find(5);

3. Trigger the Event

Manually trigger the event for the found transaction. For example, if you have an event called NewTransaction, you can trigger it like this:

\App\Events\NewTransaction::dispatch($transaction);

Or you can run

event(new \App\Events\NewTransaction($transaction));

Hope this one will help you one day!