Laravel 5 Event and Listener Simple Example

Laravel 5 Event and Listener Simple Example:


1.In the app/providers/EventServiceProvider.php

In the $listen variable add:
  'App\Events\NewOrder' => [  //NewOrder is event Class Name

            'App\Listeners\NewOrderNotification',   // NewOrderNotification is the Listner Name

        ], 

2. Write the command that will generate the files in the events and the listner folders:



php artisan event:generate

So this will generate the new file in app/events/NewOrder.php and in the app/listner/NewOrderNotification.php

 3.Now for just testing purpose in the route write this code:

    use App\Events\NewOrder;

    Route::get('test', function () {

    Event::fire(new NewOrder()); // Fires the event.

    return "event fired";});

4. So this will call the Listner/NewOrderNotification.php handle function so in the handle funtion write this code:


    public function handle(NewOrder $event)

    {

       // redirect('get_latest_orders');

        dd('hello');



    }
5. You see that you will get the output hello in the screen. So for firing the event just call like this in any controller:

use App\Events\NewOrder;

Event::fire(new NewOrder());

So this is the simplest tutorial for the event listner example in the laravel 5.3. You can also use Laravel Pusher for sending the live notifications to the browsers.



Comments