请求验证之前的输入操作

Input manipulation before request validation

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

$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',
    ];
}

您正在 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]
    ]);
}

从这个问题我假设

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

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

如果是这种情况,您需要从请求文件中删除 towncity 的验证规则,之后您将不会收到这些字段的验证错误。 此外,您需要在 ClientRequest class.

rules() 方法中为 citytown 字段添加适当的验证规则

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