Skip to content

Latest commit

 

History

History
58 lines (40 loc) · 1.87 KB

events.md

File metadata and controls

58 lines (40 loc) · 1.87 KB

Events

Eloquent models dispatch several events, allowing you to hook into the following moments in a model's lifecycle: retrieved, creating, created, updating, updated, saving, saved, deleting, deleted, trashed, forceDeleting, forceDeleted, restoring, restored, and replicating.

📘 The following few lines explain how to use events with the library, if you want to know more you can look at the documentation: Eloquent - Events.

How to use Eloquent events ?

By default, Eloquent events are not functional in the library since Eloquent is initially used with Laravel which contains all the logic to dispatch the events. However, it is possible to use events via the illuminate/events library.

  1. First, install illuminate/events :
composer require illuminate/events ^10.0
  1. Setup the dispatcher in your model with setEventDispatcher function :
use Illuminate\Events\Dispatcher;
use Dbout\WpOrm\Orm\AbstractModel;

class User extends AbstractModel 
{

    protected static function boot()
    {
        static::setEventDispatcher(new Dispatcher());
        parent::boot();
    }
}
  1. Create your events :)
use Illuminate\Events\Dispatcher;
use Dbout\WpOrm\Orm\AbstractModel;

class User extends AbstractModel 
{

    protected static function boot()
    {
        static::setEventDispatcher(new Dispatcher());
        parent::boot();
        
        static::saved(function (User $user) {
            // Add your logic here
        });
    }
}

You can now use events, you can use $dispatchesEvents property or closures.

Warning, if you use abstract class, you must call setEventDispatcher in child class.