Sunday, October 9, 2016

Simple Event-Listener Example in Laravel 5.3

So mmm....Let's create an event first by executing this command :
"php artisan make:event hisoka_event"
We will gonna see a new file in our events dir like this one :
Next... Create a listener for this event, type :
php artisan make:listener hisoka_listener --event="hisoka_event"
Result :

Next... let's register this event and it's listener to EventServiceProvider. Open eventServiceProvider.php in app/Providers/EvenServiceProvider.php, then add this line :
That will make our event and it's listener get connected each other, so when hisoka_event get's fired, hisoka_listener will gonna be executed...Next... Let's fire this event, we will gonna put it on a controller. For example here, it will be put on my HisokaController.php as shown below :
So we just need to trigger this controller when a link is clicked or another thing that we can use to do that... :D..... mmm... here I will just put it to a link like this :

Sooowh... The last thing we have to do is creating a route for hisoka_event :

Okiee... Let's try to run our awesome hisoka_event...
So when we click "Trigger hisoka event", our event will be executed and the route back to this page, but currently we can't see anything because we just put an empty event-listener here...wkwkwk...
So let's add this line to our listener :

Aaaand... let's hit the hisoka_event link again... then open laravel log... We'll gonna see our above log :


Soooo... That's all... Thank you for reading my post... ;)

1 comment:

  1. Ini tutorial yang singkat, padat, jelas langsung ke inti. Nyari kesana kemari tentang implementasi event listener, cuma tulisan ini yang masuk di otak. Good job.

    ReplyDelete