Laravel Livewire 模型属性绑定

时间:2021-06-27 11:17:49

标签: laravel laravel-livewire

这是我的 Livewire 组件

<?php

namespace App\Http\Livewire\Dashboard;

use App\Models\Post;
use Livewire\Component;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class EditPost extends Component
{
    use AuthorizesRequests;

    public ?Post $postSingle = null;

    protected $rules = [
        'postSingle.priority' => 'digits_between:1,5',
    ];

    public function setPriority(Post $postSingle, $priority)
    {
        $this->authorize('update', $postSingle);
        $this->postSingle->priority = $priority;
    }

}

在我的刀片视图中,我有 <button wire:click="setPriority({{ $postSingle->id }}, 4)"></button>

在其他地方我用 {{ $postSingle->priority }}

显示优先级

我不直接用 wire:model="postSingle.priority" 进行模型属性绑定的原因是我想运行 $this->authorize('update', $postSingle);

下面的代码发生的情况是,如果我单击按钮,刀片视图中的 $postSingle->priority 会更新,但我的数据库中的 Post 记录不会更新。我错过了什么?

1 个答案:

答案 0 :(得分:0)

您似乎忽略了实际保存记录。

public function setPriority(Post $postSingle, $priority)
{
    $this->authorize('update', $postSingle);
    $this->postSingle->priority = $priority;

    // save the record
    $this->postSingle->save();
}