I have an audit class which extends the Eloquent Model...
class Audit extends Model {
}
I have an auditable interface...
interface IAuditiable {
public function audit();
}
I have a trait which fulfils the interface and defines the relation between the model and the audit...
trait Auditable {
public function audit(){
return $this->hasMany('Audit');
}
}
I have a model which extends the Eloquent Model implements the interface and uses the trait...
class Post extends Model implements IAuditable {
use Auditable;
}
I'd like to add the functionality in there to create
or update
an audit whenever the Post model is created or updated. I've solved this by registering an observer on the Post which would catch the 'saved' event and add a new audit.
However, there will eventually be many models using implementing IAuditable
and using the Auditable
trait.
So, my question is, is it possible to implement an observer which would pick up all 'saved' events for any model which implements the IAuditable
interface in Laravel 5.1?
This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function. Think of it like this: when you don't exactly know what a query will return then you need to use get() .
Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.
Some of the features due to which it is famous are Soft deleting, Timestamps, ActiveRecord implementation, multiple database handling, eager loading, model observers, model events, and much more. Eloquent relationships are the same as the method in Eloquent model classes.
In Laravel, an interface is a contract for what methods will be used in a specific class. Actually, interfaces are not specific to Laravel, or even native PHP for that matter. Since we've been on a roll with Laravel, we'll talk about interfaces in Laravel.
You can try hooking into eloquent events. Do something like this in a service provider:
Event::listen(['eloquent.created: *', 'eloquent.updated: *'], function($model) {
// Check if the model implements your interface (could use class_implements(...)
});
I had to do something very similar to what you're looking to do. This solution isn't perfect because you catch events from every model, but it works well enough.
EDIT: Just noticed this question was asked almost two years ago. Hopefully this helps someone out, though :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With