Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Observers - Any way to pass additional arguments?

So I'm using the Laravel model event observerables to fire custom event logic, but they only accept the model as a single argument. What I'd like to do is call a custom event that I can also pass some extra arguments to that would in turn get passed to the Observer method. Something like this:

    $this->fireModelEvent('applied', $user, $type);

And then in the Observer

    /**
     * Listen to the applied event.
     *
     * @param  Item    $item
     * @param  User    $user
     * @param  string  $type
     * @return void
     */
    public function applied(Item $item, $user, string $type) {
       Event::fire(new Applied($video, $user, $type));
    }

As you can see i'm interested in passing a user that performed this action, which is not the one that necessarily created the item. I don't think temporary model attributes are the answer because my additional event logic gets queued off as jobs to keep response time as low as possible. Anyone have any ideas on how I could extend Laravel to let me do this?

My theory would be to do a custom trait that overrides one or more functions in the base laravel model class that handles this logic. Thought I'd see if anyone else has needed to do this while I look into it.

Also here's the docs reference

like image 878
Throttlehead Avatar asked Jan 31 '26 14:01

Throttlehead


1 Answers

I've accomplished this task by implementing some custom model functionality using a trait.

/**
 * Stores event key data
 *
 * @var array
 */
public $eventData = [];


/**
 * Fire the given event for the model.
 *
 * @param  string  $event
 * @param  bool    $halt
 * @param  array   $data
 * @return mixed
 */
protected function fireModelEvent($event, $halt = true, array $data = []) {
  $this->eventData[$event] = $data;
  return parent::fireModelEvent($event, $halt);
}


/**
 * Get the event data by event
 *
 * @param  string  $event
 * @return array|NULL
 */
public function getEventData(string $event) {
  if (array_key_exists($event, $this->eventData)) {
    return $this->eventData[$event];
  }

  return NULL;
}
like image 103
Throttlehead Avatar answered Feb 02 '26 05:02

Throttlehead



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!