【问题标题】:Input manipulation before request validation请求验证之前的输入操作
【发布时间】:2019-12-27 07:44:57
【问题描述】:

我在 Laravel 中创建了请求表单验证,但是当我想添加新的输入字段时,它不起作用。在我的表格中,没有名为城镇或城市的输入。我只想在 Controller 中添加一个。

$request->all() // returns perfect with new inputs.

$request->validated() // returns without new inputs. because of that validation fails.

ClientController.php

public function update(ClientRequest $request, Client $client)
{
    $request->merge([
        'city' => explode('/', $request->post('citytown'))[0],
        'town' => explode('/', $request->post('citytown'))[1]
    ]);

    $validated = $request->validated();

    Client::whereId($client->id)->update($validated);

    return redirect('/clients')->with('success', 'success');
}

ClientRequest.php

public function rules()
{
    return [
        'email' => "required|email|max:254|unique:clients,email,{$this->route()->client->id}",
        'fullname' => 'required|max:128',
        'idnumber' => "required|max:11|unique:clients,idnumber,{$this->route()->client->id}",
        'gender' => 'required|digits_between:1,2',
        'phone' => "required|max:10|unique:clients,phone,{$this->route()->client->id}",
        'adress' => 'required',
        'town' => 'required',
        'city' => 'required',
    ];
}

【问题讨论】:

    标签: php laravel laravel-6


    【解决方案1】:

    您正在Illuminate\Foundation\Http\FormRequest 中寻找prepareForValidation() 方法。

    $this->request->set(key, value);
    

    例子:

    protected function prepareForValidation()
    {
        $this->request->merge([
            'city' =>  explode('/', $this->request->get('citytown'))[0],
            'town' =>  explode('/', $this->request->get('citytown'))[1]
        ]);
    }
    

    【讨论】:

    • 感谢您的回答。在 prepareForValidation 方法中,$request 不起作用。我无法访问请求数据。
    • 对不起,我弄错了。您可以通过$this->request->get(key)访问请求数据。
    • 如果您在 Request 类中访问请求参数,只需使用 $this->get('key')
    • @sumit 这不是那么“简单”,而是一种速记
    【解决方案2】:

    从这个问题我假设

    1. 您的表单没有名为 towncity 的字段,但您有名为 citytown 的字段,该字段应该由用户以 CityName/TownName 格式提交

      李>
    2. 您打算通过拆分 citytown 字段仅在控制器代码中手动添加这些字段。

    如果是这种情况,您需要从请求文件中删除 towncity 的验证规则,之后您将不会收到这些字段的验证错误。 另外,您需要在ClientRequest 类的rules() 方法中为citytown 字段添加适当的验证规则。

    所以这不是验证前输入操作的情况,只需为 citytown 字段添加验证规则并将其拆分为控制器方法。

    【讨论】:

      猜你喜欢
      • 2019-07-12
      • 1970-01-01
      • 2016-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多