laravellaravel-5eloquentlaravel-events

How to add custom event to a Laravel model


I have payment model and want to fire an custom event when payment confirmed.

My model code:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Payment extends Model
{
    protected $dates = [
        'created_at', 'updated_at', 'confirmed_at',
    ];

    public function confirmed(){
        $this->setAttribute('confirmed_at', now());
        $this->setAttribute('status', 'confirmed');
    }
}

Solution

  • I can fire an confirmed event in Payment->confirmed() method, like this:

        public function confirmed(){
            // todo, throw an exception if already confirmed
    
            $this->setAttribute('confirmed_at', now());
            $this->setAttribute('status', 'confirmed');
    
            // fire custom event
            $this->fireModelEvent('confirmed');
        }
    

    And register custom event to $dispatchesEvents

     protected $dispatchesEvents = [
            'confirmed' =>  \App\Events\Payment\ConfirmedEvent::class
     ];
    

    Done. The \App\Events\Payment\ConfirmedEvent::class event will call when Model confirmed() method be called.

    It also recommended to throw an exception if confirmed() method called twice.