Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ligonsker's avatar

Am I doing it right? Passing data from Event to Listener

There isn't information about this on the docs, but this is how I currently pass data from the Event to the Listener - I set public properties on the Event, then when it's injected to the Listener handle() constructor it's available there:

// The Event
namespace App\Events

use ...

class MyEvent
{
    use ...
    
    public $some_property;
    public $some_other_property;

    public function __construct($data)
    {
        $this->some_property = $data->some_property;
        $this->some_other_property = $data->some_other_property;
    }

    // rest of the event . . .
}

And then in the listener:

// The Listener
namespace App\Listeners;

use ...

class MyListener
{
    public function handle(MyEvent $event)
    {
        // here I can access $event->some_property and $event->some_other_property
    }
}

It works, but I want to know if it really is how it's meant to be since I couldn't find it in the docs

Thanks

0 likes
5 replies
tisuchi's avatar
tisuchi
Best Answer
Level 70

@ligonsker It seems right. If you add a type hint, it will be better.

For example:

class MyEvent
{
    public SomePropertyType $some_property;
    public SomeOtherPropertyType $some_other_property;

    public function __construct(SomePropertyType $some_property, SomeOtherPropertyType $some_other_property)
    {
        $this->some_property = $some_property;
        $this->some_other_property = $some_other_property;
    }

    // rest of the event . . .
}

Have you checked this? https://laravel.com/docs/events#defining-listeners

2 likes
kokoshneta's avatar

@tisuchi If you’re on PHP8 or newer, you can also use constructor property promotion to make the code shorter and sweeter and reduce repetition:

class MyEvent {
	use …

	public function __construct(public PropTypeA $propA, public PropTypeB $propB);
}
3 likes
kokoshneta's avatar

@tisuchi Yes, PHP8 only – thought I mentioned that, but it looks like I forgot. Added!

2 likes

Please or to participate in this conversation.