3

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');
    }
}
Amin Shojaei
  • 5,451
  • 2
  • 38
  • 46

3 Answers3

6

Came across this question and found another approach that might be helpful to others.

Currently there is also an option to utilize the observers instead of having to create custom event classes.

In your model add the following property:

protected $observables = ['confirmed'];

This property is part of the HasEvents trait and will register this event as an eloquent event (eloquent.confirmed: \App\Payment).

You will now be able to add a method to the observer:

public function confirmed(Payment $payment);

You can now fire the event and the observer method will be called:

$this->fireModelEvent('confirmed');

Or outside of the model (since fireModelEvent is protected):

event('eloquent.confirmed: ' . Payment::class, $payment);
Thomas Van der Veen
  • 3,136
  • 2
  • 21
  • 36
5

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.

Amin Shojaei
  • 5,451
  • 2
  • 38
  • 46
3

You could use Attribute Events:

protected $dispatchesEvents = [
    'status:confirmed' => PaymentConfirmed::class,
];
Jan-Paul Kleemans
  • 818
  • 1
  • 12
  • 22