Create an EVENT and Listener in Laravel 7

This laravel 7 tutorial help to understand event and listeners.The laravel event allows to subscribe and listen for various events that occur in your application.

The Event classes are typically stored in the app/Events directory, while their listeners are stored in app/Listeners. By-default these directory not exist into the /app folder, It creates automatically by generating event and listeners using command lines.

How To Generate EVENT and Listener in Laravel 7

The EventServiceProvider included with your Laravel application provides a convenient place to register all of your application’s event listeners. The listen property contains an array of all events (keys) and their listeners (values).

I have already shared Events And Listeners Example Using Laravel 5.6.This tutorial help to integrate event and listener in laravel, I will also let you know to call event from controller method.

There are below method that help to create event and listener class, and stored file into the app/Events and app/Listeners directory.You can get more information from Official Docs.

Make the event and listeners class entry into the Providers/EventServiceProvider.php

protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
		'App\Events\TestEvent2' => [
        'App\Listeners\TestEventListener2',
      ],
    ];

Option 1:

php artisan event: generate

Above command will create file into respective folder like, TestEvent into app/Events and TestEventListener into app/Listeners.

Option 2:

We can also generate event and listener files by following command –

php artisan make:event TestEvent
php artisan make:listener TestEventListener --event="TestEvent"

The event File code is –

The full event file code is below –

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class TestEvent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

How To Define handle file

Now modified handle() method into App\Listeners\TestEventListener.php file, that will have some program, that will execute when the even will occurred.

namespace App\Listeners;

use App\Events\TestEvent;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;

class TestEventListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  TestEvent  $event
     * @return void
     */
    public function handle(TestEvent $event)
    {
		Log::info('=== TestEventListener  ========');
        //
		
    }
}

How To Dispatch Event In Laravel

The dispatching event is very easy in laravel, You need to just pass the event class object into event() method and event will fire when the testEvent() method will call.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Employee;

use App\Events\TestEvent;
use Illuminate\Support\Facades\Log;
use Exception;


class EmployeeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }
    public function testEvent(){
        try {
                
            Log::info('=== Hello  ========');
            event(new TestEvent());
            return response('Event has been fired Successfully!', 200)
                  ->header('Content-Type', 'text/json');

          } catch(Exception $ex) {
             Log::info('Error'. $ex->getMessage());
        
             return $ex;
          }
        }
	}

Leave a Reply

Your email address will not be published. Required fields are marked *