Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 how to listen to a model event?

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 title, how to write an event listener to have the notifying (with the post title value passing to the listener?

like image 431
JackpotK Avatar asked May 26 '13 08:05

JackpotK


People also ask

How does Laravel event listener work?

Event listeners receive the event instance in their handle method. The event:generate command will automatically import the proper event class and type-hint the event on the handle method. Within the handle method, you may perform any logic necessary to respond to the event. * Create the event listener.

Why we use events and listeners in Laravel?

Laravel's events provide a simple observer pattern implementation, allowing you to subscribe and listen for various events that occur within your application. Event classes are typically stored in the app/Events directory, while their listeners are stored in app/Listeners .


1 Answers

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.

like image 183
Rex Schrader Avatar answered Nov 11 '22 08:11

Rex Schrader