Search code examples
phplaravellaravel-4laravel-3

Laravel 4 Model events. Possible to do reading, read type event after query results are set on a model?


In Laravel 4 there are Model events for creating, created, updating, updated etc.

Has anyone found a way to do something similar to a reading, read event without hacking / extending the QueryBuilder class?

Even if it isn't an event per say, I would like to find a way to achieve this before/during/after (either one of those) query results have been injected into the model attributes.

So far I am just overriding the getAttributeFromArray method on my core/base model class which works but obviously runs the logic everytime you try to grab an attribute/property in the model (Could end up being a costly operation down the line).

Thanks!


Solution

  • I was able to achieve this by adding and overriding 1 method in my core/base model class (extends eloquent\model)

    public static function read($callback)
    {
        static::registerModelEvent('read', $callback);
    }
    
    public function setRawAttributes(array $attributes, $sync = false)
    {
    
        parent::setRawAttributes($attributes,$sync);
    
        $this->fireModelEvent('read');
    }
    

    This way my read event will only fire once when the results are injected into the model(s). instead of having the event run per __get call on the model.