Created
October 25, 2017 23:18
-
-
Save scrubmx/7fc20663ce2b3ac103a2879915b572be to your computer and use it in GitHub Desktop.
Register custom model events in laravel 5.5
This file contains 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; | |
class Application extends Model | |
{ | |
/** | |
* The attributes that should be mutated to dates. | |
* | |
* @var array | |
*/ | |
protected $dates = [ | |
'verified_at', | |
]; | |
/** | |
* These are extra user-defined events observers may subscribe to. | |
* | |
* @var array | |
*/ | |
protected $observables = [ | |
'verifying', 'verified', | |
]; | |
/** | |
* Mark an application as verified. | |
* | |
* @param array $options | |
* @return bool | |
*/ | |
public function verify(array $options = []) | |
{ | |
// If the "verifying" event returns false we bail out immediately and return | |
// false, indicating that the save failed. This provides a chance for any | |
// listeners to cancel save operations if validations fail or whatever. | |
if ($this->fireModelEvent('verifying') === false) { | |
return false; | |
} | |
if ($saved = $this->setAttribute('verified_at', $this->freshTimestamp())->save($options)) { | |
$this->fireModelEvent('verified'); | |
} | |
return $saved; | |
} | |
/** | |
* Register a verifying model event with the dispatcher. | |
* | |
* @param \Closure|string $callback | |
* @return void | |
*/ | |
public static function verifying($callback) | |
{ | |
static::registerModelEvent('verifying', $callback); | |
} | |
/** | |
* Register a verified model event with the dispatcher. | |
* | |
* @param \Closure|string $callback | |
* @return void | |
*/ | |
public static function verified($callback) | |
{ | |
static::registerModelEvent('verified', $callback); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm doing the same as you but I get Method Illuminate\Database\Query\Builder::fireModelEvent does not exist.