Ad

The Events Don't See The Listeners In Laravel

- 1 answer

I have used event and listeners before but now I'm trying to use event and listeners but the event don't see the listeners as the code below

The event

<?php

namespace App\Events;

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

class teste
{
    use Dispatchable, InteractsWithSockets, SerializesModels;


    public function __construct()
    {

    }

    public function broadcastOn()
    {
        return [new PrivateChannel('channel-name')];
    }
}

and it is the listener of the event

<?php

namespace App\Listeners;

use App\Events\teste;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class testl
{

    public function __construct()
    {
        //
    }


    public function handle(teste $event)
    {
        return true;
    }
}

and the eventProviderService

class EventServiceProvider extends ServiceProvider
{

    protected $listen = [
        // Registered::class => [
        //     SendEmailVerificationNotification::class,
        // ],
        'App\Events\teste' => [
            'App\Listeners\testl'
        ],


    ];

and the code to call the event is

Route::get("test100" , function(){
        $Event = event(new \App\Events\teste());
        dd($Event);
    });

and after all, there is no output when i use function dd() to check the output it's nothing it's empty array don't contain null or any thing and when i use function dd() in the listener to check if the event see the listener or no, the result was nothing

Ad

Answer

In order for Events and Listeners to function, you need to have mapped which Listners respond to a given Event. In Laravel, this is handled within the EventServiceProvider

The example below is taken from the Laravel documentation:

/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    'App\Events\OrderShipped' => [
        'App\Listeners\SendShipmentNotification',
    ],
];

Any number of Listeners can react to a given Event

EDIT: Also, make sure that the namespacing is correct for your application

Ad
source: stackoverflow.com
Ad