Laravel 4 how to listen to a model event?

前端 未结 4 1843
孤城傲影
孤城傲影 2020-12-30 04:09

I want to have an event listener binding with a model event updating.
For instance, after a post is updated, there\'s an alert notifying the updated post ti

4条回答
  •  旧巷少年郎
    2020-12-30 04:41

    The documentation briefly mentions Model Events. They've all got a helper function on the model so you don't need to know how they're constructed.

    Eloquent models fire several events, allowing you to hook into various points in the model's lifecycle using the following methods: creating, created, updating, updated, saving, saved, deleting, deleted. If false is returned from the creating, updating, saving or deleting events, the action will be cancelled.


    Project::creating(function($project) { }); // *
    Project::created(function($project) { });
    Project::updating(function($project) { }); // *
    Project::updated(function($project) { });
    Project::saving(function($project) { });  // *
    Project::saved(function($project) { });
    Project::deleting(function($project) { }); // *
    Project::deleted(function($project) { });
    

    If you return false from the functions marked * then they will cancel the operation.


    For more detail, you can look through Illuminate/Database/Eloquent/Model and you will find all the events in there, look for uses of static::registerModelEvent and $this->fireModelEvent.

    Events on Eloquent models are structured as eloquent.{$event}: {$class} and pass the model instance as a parameter.

提交回复
热议问题