Skip to content

Instantly share code, notes, and snippets.

@adrianb93
Last active March 18, 2018 04:12
Show Gist options
  • Save adrianb93/6f5471e5b51c91170a5d6bc28764921f to your computer and use it in GitHub Desktop.
Save adrianb93/6f5471e5b51c91170a5d6bc28764921f to your computer and use it in GitHub Desktop.
In-Model Event Observers for Laravel Models.
<?php
namespace App\Models\Traits;
use Illuminate\Support\Str;
trait RegisterInModelEvents
{
/**
* Register in-model event observers. This is to avoid creating a seperate
* observer file for a single event. Will match any method matching the
* `on[ObservableEvent]` and register it as a listener on the event.
*
* For example, onCreating(); onCreated(); onUpdating(); onUpdated();
* onDeleting(); onDeleted(); onSaving(); onSaved(); onRestoring();
* onRestored(); etc. It also supports added observable events.
*
* @return void
*/
protected static function bootRegisterInModelEvents()
{
$instance = new static;
foreach ($instance->getObservableEvents() as $event) {
$method = 'on'.Str::ucfirst($event);
if (method_exists($instance, $method)) {
static::registerModelEvent($event, static::class.'@'.$method);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment