How use Laravel's Bootable Eloquent Traits
Given the following bootable trait:
```php
trait WithCreator
{
//no need to define a 'boot' method
public static function bootWithCreator()
{
self::observe(CreatorObserver::class);
}
}
```
```php
class CreatorObserver
{
public function creating($model)
{
$model->creator()->associate(auth()->user());
}
}
```
We can use it to register the observer without colliding with existing boot methods inside the model.
```php
class Comment extends Model
{
use HasFactory;
use WithCreator;
public static function boot()
{
...
}
}
```
Denisa Halmaghi
10 Dec 2021
« Back to post