Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel : one observer for multiple models

Tags:

php

laravel

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?

like image 583
astroame Avatar asked Dec 23 '22 19:12

astroame


1 Answers

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';
        });
    }
}
like image 176
Elias Soares Avatar answered Jan 08 '23 21:01

Elias Soares