laravel未触发特征中的模型事件

ovfsdjhp  于 2022-12-05  发布在  其他
关注(0)|答案(2)|浏览(188)

为什么这个不起作用??还有什么我需要做的吗???(注:我不想从model中调用任何boot方法)。在模型中,它与booted方法一起工作得很好

// 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());
        });
    }
}
jei2mxaa

jei2mxaa1#

如果我想从trait中激发模型事件,我得到了答案:我必须将 Boot 方法名称设置为带有前缀boot的特征类名
例如:如果我的特征名称是Sortable,则 Boot 方法名称将是bootSortable以下是该问题的完整解决方案:

// 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());
        });
    }
}
kxxlusnw

kxxlusnw2#

你可以使用laravel观测器,它要简单得多

相关问题