模型静态::创建取消无法正常工作

问题描述 投票:0回答:1

我正在使用 Laravel、Livewire、FilamentPHP。

在我的模型中

protected static function boot(): void
    {
        parent::boot();
        static::creating(function ($model) {
            $uuid = Uuid::uuid4();

            $reservation = Reservation::where('reservation_date', now()->format("Y-m-d"))->where('user_id', $model->user_id)->first();
            if (!$reservation?->id) {
                Notification::make()->title("This user doesn't have a reservation.")->danger()->send();
                return false;
            }
            $model->reservation_id = $reservation->id;
            return false;

            $model->order_uuid = $uuid->toString();
        });
    }

然后当我将代码块更改为 ->

protected static function boot(): void
    {
        parent::boot();
        static::creating(function ($model) {
            $uuid = Uuid::uuid4();

            $reservation = Reservation::where('reservation_date', now()->format("Y-m-d"))->where('user_id', $model->user_id)->first();
            if (!$reservation?->id) {
                Notification::make()->title("This user doesn't have a reservation.")->danger()->send();
                return false;
            } else {
                $model->reservation_id = $reservation->id;
                $model->order_uuid = $uuid->toString();
            }

        });
    }

然后这次它抛出我->缺少[路由:filament.admin.resources.orders.edit] [URI:admin/orders/{record}/edit] [缺少参数:record]所需的参数。错误。

我希望每当没有 $reservation->id 时它都会发送通知并停止保存。但在现实中它又回到了我:

  • 404 未找到页面(“我希望它只是发送我想要的通知,而不是返回此页面”)

  • 手动刷新页面后,显示 2 条通知 -> 模型已创建通知 & 该用户没有预订通知。

我在这里做错了什么?有人可以帮助我吗?

laravel eloquent laravel-livewire laravel-filament filamentphp
1个回答
0
投票

我认为你不应该将逻辑放在模型事件中,而应该放在检查预订是否存在的函数中:


$reservation = Reservation::where('reservation_date', now()->format("Y-m-d"))->where('user_id', $user->id)->first();
            if (!$reservation) {
                Notification::make()->title("This user doesn't have a reservation.")->danger()->send();
            } else {  
                // create your object 
            }

您的模型不应该处理其创建的验证逻辑

© www.soinside.com 2019 - 2024. All rights reserved.