FEATURE REQUEST: Register Model Observers via Model property. #34502
Replies: 4 comments 1 reply
-
I believe this is possible already. |
Beta Was this translation helpful? Give feedback.
-
Bump. Would definitely like to have this in the framework without having to use Registering observers in the EventServiceProvider makes it harder to debug. |
Beta Was this translation helpful? Give feedback.
-
I created a trait called Example: namespace App\Models\Traits;
use RuntimeException;
/**
* @mixin \Illuminate\Database\Eloquent\Model
*/
trait Observable
{
public static function bootObservable(): void
{
$baseName = class_basename(static::class);
$observableClass = "\\App\\Observers\\{$baseName}Observer";
if (! class_exists($observableClass)) {
throw new RuntimeException("Observer class {$observableClass} does not exist.");
}
(new static())->registerObserver($observableClass);
}
} I will try to create a package for it somewhere next week. |
Beta Was this translation helpful? Give feedback.
-
It's now possible to do this with PHP Attributes. https://laravel.com/docs/10.x/eloquent#observers |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Typically, model observers are registered in a service provider or in the model itself via an overloaded
boot()
method that looks like this:This request seems pretty obvious, so there's probably something that I've missed, but could the base
boot()
method be updated to call abootObservers()
method -- similar to thebootTraits()
method -- that will process an$observers
array property so that the above can be avoided and replaced with something that looks like this:(I made it an array and plural since I can't recall if there's support or need for multiple observers on a single model. It can easily be singular if that makes the most sense.)
Beta Was this translation helpful? Give feedback.
All reactions