简体   繁体   English

如何在Laravel 5.5上的表单请求中将实体ID传递给唯一验证?

[英]How to pass the entity id to the unique validation in a Form Request on Laravel 5.5?

I have the following route defined: 我定义了以下路线:

Route::put('/{organisationId}', 'OrganisationController@update');

And I have the following FormRequest for the update request: 我有以下FormRequest用于更新请求:

<?php

namespace App\Http\Requests\Organisation;

use Illuminate\Foundation\Http\FormRequest;

class UpdateOrganisationRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'required|min:3|max:60|unique:organisations,name,' . $this->get('organisationId')
        ];
    }
}

And I am trying to use it like this in my controller: 我试图在控制器中像这样使用它:

public function update($organisationId, UpdateOrganisationRequest $request)
{
    $organisation = $this->organisationRepository->byId($organisationId);

    if (!$organisation) {
        return $this->error('Organisation not found.', $this::Bad_Request);
    }

    $this->organisationRepository->update($organisation, $request->validated());

    return $this->success(
        fractal($organisation, new OrganisationTransformer())
    );
}

This appears to trigger the unique validation error, because it doesn't appear to exclude the id I am trying to update. 这似乎触发了唯一的验证错误,因为它似乎没有排除我要更新的ID。

Any ideas why this isn't working? 任何想法为什么这不起作用?


Before using FormRequest , this is how I implemented the same functionality above and it was working fine: 在使用FormRequest之前,这是我实现上述相同功能的方式,并且工作正常:

https://pastebin.com/raw/CDEg6qLt https://pastebin.com/raw/CDEg6qLt

I was able to update the same organisation with the same name and the unique validation rule didn't trigger an Validation exception. 我能够用相同的名称更新相同的组织,并且唯一的验证规则未触发验证异常。

All rules defined in a FormRequest 's rules method should be in form of a key / value pair that corresponds to an input name and it's validation rule respectively. FormRequestrules方法中定义的所有规则应采用键/值对的形式,分别对应于输入名称及其验证规则。 You missed key here so chances are validator looks for a field named 0 that doesn't exist. 您在此处错过了key ,因此验证程序很可能会查找不存在的名为0的字段。

Add name and test result: 添加名称和测试结果:

return [ 'name' => '....' ];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM