Search code examples
phplaraveleventslaravel-5.3

How can I pass a variable to an event that isn't a class instance?


I have an Event that I fire when someone favourites an entity on my system. This is fired using Event::fire(new AddedAsFav($entity_id));.

In that event I want to pull some info about that $entity_id. To do this I believe I need to pass the $entity_id as part of the constructor of my Listener and then I can access it. Unfortunately the constructor expects a type, and I can't seem to pass just an integer. The docs have lots of examples where they pass Eloquent ORM instances, which is prefixed with the name of the class (Entity $entity, for example). But I don't want to pass a full object, just an ID, as the controller it's coming from only has an ID. I'd rather do the query (which is expensive and time consuming, hence the event) in the event itself.

So how can I pass and access a basic int?

Here's my listener:

<?php

namespace App\Listeners;

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

class GetFullEntity
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct(int $entity_id)
    {
        $this->entity_id = $entity_id;
    }

    /**
     * Handle the event.
     *
     * @param  MovieAddedAsToWatch  $event
     * @return void
     */
    public function handle(AddedAsFav $event)
    {
        dd($event);
    }
}

Solution

  • You only type cast something you may want to use in the listener.

    if you want to simply access the data/object/array you passed to the event class, assign it to a public property in the event class:

    class AddedAsFav extends Event
    {
    
        public $entity_id;
    
        public function __construct($entity_id)
        {
    
            $this->entity_id = $entity_id;
    
        }
    }
    

    You can now access it in your listener like any property:

    <?php
    
    namespace App\Listeners;
    
    use App\Events\AddedAsFav;
    use Illuminate\Queue\InteractsWithQueue;
    use Illuminate\Contracts\Queue\ShouldQueue;
    
    class GetFullEntity
    {
        /**
         * Create the event listener.
         *
         * @return void
         */
        public function __construct()
        {
    
        }
    
        /**
         * Handle the event.
         *
         * @param  MovieAddedAsToWatch  $event
         * @return void
         */
        public function handle(AddedAsFav $event)
        {
            $entity_id = $event->entity_id;
        }
    }