I have multiple model that have same logic oncreated method, can I have one observer for that? Or another approach just to avoid creating multiple Observers for each model?
You can use a bootable trait for this purpose.
<?php
namespace App\Traits;
trait MyModelTrait
{
public static function bootMyModelTrait()
{
static::created(function ($model) {
$model->someField = 'someLogicValue';
});
}
}
You may register Closure based events manually in the boot method of your EventServiceProvider:
/**
* Register any other events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();
Event::listen(['eloquent.saved: *', 'eloquent.created: *', ...], function($context) {
// dump($context); ---> $context hold information about concerned model and fired event : e.g "eloquent.created: App\User"
// YOUR CODE GOES HERE
});
}
我会为每个模型保留一个观察者,而是提取具有通用功能的 Trait/基类/服务类,然后您可以在这些观察者中使用这些功能。
This is much better when you apply this in provider, so in the future you can easily remove if laravel provide a better way.
currently we using laravel v8.42.1, but this seems applicable in older version.
namespace App\Providers;
use App\Observers\GlobalObserver;
use App\Models\Product;
class ObserverServiceProvider extends ServiceProvider
{
public function register()
{
//
}
public function boot()
{
self::registerGlobalObserver();
}
private static function registerGlobalObserver()
{
/** @var \Illuminate\Database\Eloquent\Model[] $MODELS */
$MODELS = [
Product::class,
// ...... more models here
];
foreach ($MODELS as $MODEL) {
$MODEL::observe(GlobalObserver::class);
}
}
}
Then this will be your observer
<?php
namespace App\Observers;
use Illuminate\Database\Eloquent\Model;
class GlobalObserver
{
public function updated(Model $model)
{
// ...
}
public function created(Model $model)
{
// ...
}
public function deleted(Model $model)
{
// ...
}
public function forceDeleted(Model $model)
{
// ...
}
}
Then register the provider in config/app.php
in providers
key
'providers' => [
\App\Observers\GlobalObserver::class,
// ...
],
the good this about this is you never go to the multiple model class just to modify them
您可以为此使用 Observer 类https://laravel.com/docs/6.x/eloquent#observers
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.