Laravel

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

Related Post

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;
          }
        }
 }

Recent Posts

What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More

2 months ago

Laravel Table Relationship Methods With Example

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More

2 months ago

Exploring the Power of Laravel Eloquent Join?

We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More

2 months ago

Quick and Easy Installation of Laravel Valet

in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More

3 months ago

What is Laravel Soft Delete and How Does it Work?

I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More

3 months ago

Common Practices for Laravel Blade Template

in this Laravel tutorial, I will explore common practices for using the Laravel Blade template with examples. Blade is a… Read More

3 months ago

Categories