【问题标题】:How to use Laravel Requests in Livewire Components如何在 Livewire 组件中使用 Laravel 请求
【发布时间】:2021-04-28 03:04:45
【问题描述】:

如何在 Livewire 组件中使用我在 Laravel 请求中使用的完全相同的规则?我已经在 Laravel 中构建了 Request,我不想在 Livewire 中重新构建它。在 Livewire 中,我不能使用 Laravel 选项(例如 \App\Rules)。因为我们也有通过控制器的 api 调用,所以解决这个问题的最佳方法是什么?

【问题讨论】:

  • 你的意思是你不能使用App\Rules?一些包含您问题的代码会更容易回答。

标签: php laravel laravel-livewire


【解决方案1】:

我假设你的意思是Laravel Form Requests。默认情况下 this feature is not possible 在 Livewire 中使用。

但是,如果您的 Livewire 组件中有 update 方法,您可以执行以下操作。

public function update(ProfileUpdateRequest $request)
{
    $this->validate($request->rules());

    // ...
}

您可以将验证捆绑在表单请求类中。

您还可以在 rules() 方法 Livewire 组件中使用您的单个规则

use App\Rules\CustomRule;

//.. other stuff

public function rules()
{
    return [
        'name' => ['required', new CustomRule()],
        'content' => 'required|min:10'
    ];
}

详情请见Livewire Validation

【讨论】:

  • 我更新了我的评论以反映 rules() 方法而不是 rules 属性。这使您可以使用现有的规则。
【解决方案2】:

你需要使用rules()作为方法而不是属性

use Illuminate\Validation\Rule;


public function rules()
{
    return [
        'name' => ['required', new MyRule()],
        'content' => 'required|min:10'
    ];
}

【讨论】:

    猜你喜欢
    • 2020-12-30
    • 2021-11-17
    • 1970-01-01
    • 2021-11-07
    • 2021-08-18
    • 2022-07-06
    • 2021-02-14
    • 2020-06-16
    • 2023-01-16
    相关资源
    最近更新 更多