Laravel 包含一个名为 ConvertEmptyStringsToNull
的全局中间件
使用中间件,对 GET/somewhere?something
的请求会导致 something === null
如果没有中间件,此请求会导致 something === ''
如何针对特定属性名称禁用它?
例如,如果您查看另一个全局包含的中间件 TrimStrings
您会注意到它包含一个 except
属性。
/**
* The attributes that should not be trimmed.
*
* @var array
*/
protected $except = [
//
];
在这种情况下,中间件将应用于除此处指定的属性之外的所有属性。我尝试以相同的方式扩展 ConvertEmptyStringsToNull
,但它不起作用。我觉得我缺少一些基本的东西。
我希望能够为此中间件添加异常(exception),以便我仅获得特定属性名称的空字符串。例如除了豁免
GET/somewhere?something
:something === null
GET/somewhere?exemption
:exemption === ''
GET/somewhere?everything
:everything === null
最佳答案
事实上,您可以扩展 TransformsRequest
类作为自定义中间件(因为 ConvertEmptyStringsToNull
也扩展了同一个类),然后重写 transform()
方法根据您的需要。一个工作示例如下
我将排除请求字段“abc”设置为 null。抱歉,不干净示例,我使用了一个数组,以防万一我想排除多个字段。
//this is a middleware class I have removed `handle()` function leaving the default.
class NinjaAuther extends TransformsRequest
{
/**
* Transform the given value.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function transform($key, $value)
{
if(is_string($value) && !in_array($key, ['abc'], true)) {
$value = $value === '' ? null : $value;
}
return $value;
}
}
从 $middleware
中删除 ConvertEmptyStringsToNull
中间件,然后添加您自己的 NinjaAuther 中间件。
那么你就可以出发了!所有请求都会通过您的自定义中间件!您可以根据需要在各个组的中间件上使用它(如果您不想将其应用于所有请求)
PS: I didn't really inspect cautiously the TransformRequest class but I think it should be safe, since anyway its being applied on all request in the default configuration inside Kernel.php
关于php - 如何忽略 Laravel 的 ConvertEmptyStringsToNull 中的特定属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46244438/