首页 > 解决方案 > 当请求被同名的表单参数覆盖时,从请求中获取url参数

问题描述

在我的项目中,我通过请求类进行验证。这是有问题的类之一:

<?php namespace App\Modules\Store\Validation\Resources\AttributeValue;

use App\Modules\Base\Services\Normalization;
use Illuminate\Foundation\Http\FormRequest;

class UpdateRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'normal' => (
                'required|string|max:255|' .
                'unique:attributes,normal,' . $this->value .
                ',id,store_id,' . $this->user()->store_id
            ),
            'title' => 'required|string|max:255',
            'value' => 'required|string|max:255',
            'reference' => 'sometimes|nullable|string|max:255',
        ];
    }

    /**
     * Authorization is in the policies
     * 
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    protected function prepareForValidation()
    {
        $this->merge([
            'normal' => Normalization::lowerCaseEnglishAlphaNum($this->normal),
        ]);
    }
}

以下是php artisan route:list使用此验证类的路由的输出:

| | PUT|PATCH | store/attribute/{attribute}/value/{value} | Store::attribute.value.update | App\Modules\Store\Controllers\StoreAttributeValueController@update                        | web,auth:store,Closure |

如您所见,路由参数的名称与表单参数之一的名称相同。value由于 form 参数覆盖了 route 参数,这会导致 normal 的唯一规则出现问题value

我宁愿不必更改参数的名称,因为它们具有相当的描述性。相反,我希望能够指定我想要路由参数而不是表单参数。

那么如何从Request对象中只获取路由参数呢?

标签: laravelvalidationparametersroutesrequest

解决方案


推荐阅读