Home > front end >  laravel model event from trait not firing
laravel model event from trait not firing

Time:12-04

why this is not working?? anything else i need to doo??? (note: i don't want to call any boot method from model). in models its working fine with booted method

// route
Route::get('/tests', function () {

    return Test::find(1)->update([
        'name' => Str::random(6)
    ]);
});

// models
namespace App\Models;

use App\Http\Traits\Sortable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Test extends Model
{
    use HasFactory;
    use Sortable;
    protected $guarded = ["id"];
}

// traits
namespace App\Http\Traits;

trait Sortable
{

    protected static function bootSort()
    {
        static::updated(function ($model) {
            dd("updated", $model->toArray());
        });
        static::updating(function ($model) {
            dd("updating", $model->toArray());
        });
        static::saving(function ($model) {
            dd("saving", $model->toArray());
        });
        static::saved(function ($model) {
            dd("saved", $model->toArray());
        });
    }
}

CodePudding user response:

I got the answer if I want to fire model event from trait: I have to make the boot method name as trait class name with prefix boot

for example: if my trait name is Sortable the boot method name will be bootSortable below is the full solution to question:

// route
Route::get('/tests', function () {

    return Test::find(1)->update([
        'name' => Str::random(6)
    ]);
});

// models
namespace App\Models;

use App\Http\Traits\Sortable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Test extends Model
{
    use HasFactory;
    use Sortable;
    protected $guarded = ["id"];
}

// traits
namespace App\Http\Traits;

trait Sortable
{
    // before
    protected static function bootSort()
    // after fix
    protected static function bootSortable()
    {
        static::updated(function ($model) {
            dd("updated", $model->toArray());
        });
        static::updating(function ($model) {
            dd("updating", $model->toArray());
        });
        static::saving(function ($model) {
            dd("saving", $model->toArray());
        });
        static::saved(function ($model) {
            dd("saved", $model->toArray());
        });
    }
}

CodePudding user response:

you can use laravel observers, it's much more simpler

  • Related