Last active
March 18, 2018 04:12
-
-
Save adrianspacely/6f5471e5b51c91170a5d6bc28764921f to your computer and use it in GitHub Desktop.
In-Model Event Observers for Laravel Models.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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