Laravel 4 how to listen to a model event?

前端 未结 4 1822
孤城傲影
孤城傲影 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条回答
  • This post: http://driesvints.com/blog/using-laravel-4-model-events/

    Shows you how to set up event listeners using the "boot()" static function inside the model:

    class Post extends eloquent {
        public static function boot()
        {
            parent::boot();
    
            static::creating(function($post)
            {
                $post->created_by = Auth::user()->id;
                $post->updated_by = Auth::user()->id;
            });
    
            static::updating(function($post)
            {
                $post->updated_by = Auth::user()->id;
            });
        }
    }
    

    The list of events that @phill-sparks shared in his answer can be applied to individual modules.

    0 讨论(0)
  • 2020-12-30 04:31
    Event::listen('eloquent.created: ModelName', function(ModelName $model)   {
        //...
    })
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-30 04:55

    I got stuck on this because I assumed subscribing to default model events like Event:listen('user.created',function($user) would have worked (as I said in a comment). So far I've seen these options work in the example of the default model user created event:

    //This will work in general, but not in the start.php file
    User::created(function($user).... 
    //this will work in the start.php file
    Event::listen('eloquent.created: User', function($user).... 
    
    0 讨论(0)
提交回复
热议问题