laravel Livewire 3如何自动将数据分配给公共属性?

koaltpgm  于 2023-11-20  发布在  其他
关注(0)|答案(1)|浏览(117)

我想问是否有一个更好的方法来创建一个更新表单使用livewire 3?我目前的代码似乎不有效,如果它有很多属性在一个表单

public function openModalAkuisisi($uuid)
{
    $this->reloadData();

    $this->outlet = Outlet::akuisisi()->with(['regional', 'area', 'horecaGroup', 'horecaOutlet', 'statusTracking'])->whereUuid($uuid)->firstOrFail();

    $this->tp_code = $this->outlet->tp_code;
    $this->outlet_code = $this->outlet->outlet_code;
    $this->outlet_name = $this->outlet->outlet_name;
    $this->alamat = $this->outlet->alamat;
    ....
    ....
    ....
    ....

    $this->dispatch('open_modal');
}

字符串
有没有更好的方法可以直接从Eloquent中为公共属性赋值,而不需要逐个写入它们?也许可以使用https://livewire.laravel.com/docs/forms提取验证规则数据?

$this->outlet = Outlet::akuisisi()->with(['regional', 'area', 'horecaGroup', 'horecaOutlet', 'statusTracking'])->whereUuid($uuid)->firstOrFail();
$this->form = $this->outlet;


所以.

bttbmeg0

bttbmeg01#

您可以使用Livewire提供的批量分配。
在你的例子中,它看起来像这样:

public function openModalAkuisisi(string $uuid): void
{
    $this->reloadData();

    $this->outlet = Outlet::akuisisi()
        ->with(['regional', 'area', 'horecaGroup', 'horecaOutlet', 'statusTracking'])
        ->whereUuid($uuid)
        ->firstOrFail();

    $this->fill($this->outlet->only([
        'tp_code',
        'outlet_code',
        'outlet_name',
        'alamat',
        // ... Add other properties
    ]));

    $this->dispatch('open_modal');
}

字符串
如果你想把它放到一个Livewire表单中,你可以做同样的事情:

namespace App\Livewire\Forms;

use App\Models\Outlet;
use Livewire\Form;

final class OutletForm extends Form
{
    public Outlet $outlet;

    public string $tp_code;
    public string $outlet_code;
    public string $outlet_name;
    public string $alamat;
    // ... Define all the properties.

    public function set(Outlet $outlet): void
    {
        $this->outlet = $outlet;

        $this->fill($outlet->only([
            'tp_code',
            'outlet_code',
            'outlet_name',
            'alamat',
            // ... Add other properties
        ]));
    }
}


你的Livewire组件看起来像这样:

namespace App\Livewire;

use App\Livewire\Forms\OutletForm;
use App\Models\Outlet;
use Livewire\Component;

final class EditarOutlet extends Component
{
    public OutletForm $form;

    public function openModalAkuisisi(string $uuid): void
    {
        $this->reloadData();

        $this->outlet = Outlet::akuisisi()
            ->with(['regional', 'area', 'horecaGroup', 'horecaOutlet', 'statusTracking'])
            ->whereUuid($uuid)
            ->firstOrFail();

        $this->form->set($outlet);

        $this->dispatch('open_modal');
    }

    // Other methods of your component
}

相关问题