Laravel 验证器未返回密钥
Laravel Validator Not Returning Key
我正在为我们的项目创建一个新的 API 调用。
我们有一个 table 不同的语言环境。例如:
ID Code
1 fr_CA
2 en_CA
但是,当我们调用 API 创建发票时,我们不想发送 ID,而是发送代码。
这是我们要发送的对象的示例:
{
"locale_code": "fr_CA",
"billing_first_name": "David",
"billing_last_name": "Etc"
}
在我们的控制器中,我们使用扩展名为 FormRequest
:
的函数将 locale_code
修改为 locale_id
// This function is our method in the controller
public function createInvoice(InvoiceCreateRequest $request)
{
$validated = $request->convertLocaleCodeToLocaleId()->validated();
}
// this function is part of ApiRequest which extend FormRequest
// InvoiceCreateRequest extend ApiRequest
// So it goes FormRequest -> ApiRequest -> InvoiceCreateRequest
public function convertLocaleCodeToLocaleId()
{
if(!$this->has('locale_code'))
return $this;
$localeCode = $this->input('locale_code');
if(empty($localeCode))
return $this['locale_id'] = NULL;
$locale = Locale::where(Locale::REFERENCE_COLUMN, $localeCode)->firstOrFail();
$this['locale_id'] = $locale['locale_id'];
return $this;
}
如果我们在函数内部转储 $this->input('locale_id')
,它会 return 正确的 ID (1)。但是,当它通过 validated();
时,它不会 return locale_id
即使它是规则的一部分:
public function rules()
{
return [
'locale_id' => 'sometimes'
];
}
我也尝试了合并、添加、设置等功能,但没有任何效果。
有什么想法吗?
FormRequest
会在到达控制器之前 运行。所以在控制器中尝试这样做是行不通的。
你可以这样做的方法是在 FormRequest
class.
中使用 prepareForValidation() 方法
// InvoiceCreateRequest
protected function prepareForValidation()
{
// logic here
$this->merge([
'locale_id' => $localeId,
]);
}
我正在为我们的项目创建一个新的 API 调用。
我们有一个 table 不同的语言环境。例如:
ID Code
1 fr_CA
2 en_CA
但是,当我们调用 API 创建发票时,我们不想发送 ID,而是发送代码。
这是我们要发送的对象的示例:
{
"locale_code": "fr_CA",
"billing_first_name": "David",
"billing_last_name": "Etc"
}
在我们的控制器中,我们使用扩展名为 FormRequest
:
locale_code
修改为 locale_id
// This function is our method in the controller
public function createInvoice(InvoiceCreateRequest $request)
{
$validated = $request->convertLocaleCodeToLocaleId()->validated();
}
// this function is part of ApiRequest which extend FormRequest
// InvoiceCreateRequest extend ApiRequest
// So it goes FormRequest -> ApiRequest -> InvoiceCreateRequest
public function convertLocaleCodeToLocaleId()
{
if(!$this->has('locale_code'))
return $this;
$localeCode = $this->input('locale_code');
if(empty($localeCode))
return $this['locale_id'] = NULL;
$locale = Locale::where(Locale::REFERENCE_COLUMN, $localeCode)->firstOrFail();
$this['locale_id'] = $locale['locale_id'];
return $this;
}
如果我们在函数内部转储 $this->input('locale_id')
,它会 return 正确的 ID (1)。但是,当它通过 validated();
时,它不会 return locale_id
即使它是规则的一部分:
public function rules()
{
return [
'locale_id' => 'sometimes'
];
}
我也尝试了合并、添加、设置等功能,但没有任何效果。
有什么想法吗?
FormRequest
会在到达控制器之前 运行。所以在控制器中尝试这样做是行不通的。
你可以这样做的方法是在 FormRequest
class.
// InvoiceCreateRequest
protected function prepareForValidation()
{
// logic here
$this->merge([
'locale_id' => $localeId,
]);
}