[英]Laravel request int and string keys weird behaviour
Imagine - Laravel application, a get requst is made. 想象一下-Laravel应用程序,获取请求。
The situation is, that a custom request, which has inputs with integer names, is made. 情况是,将创建一个具有整数名称输入的自定义请求。 In the custom request file I'm adding another field, lets say "fields".
在自定义请求文件中,我要添加另一个字段,例如“ fields”。 So at first the
$request->all()
returns 所以首先
$request->all()
返回
array(
1 => "value1",
5 => "value5",
12 => "value12",
)
and after adding the new field $request->all()
returns 在添加新字段
$request->all()
返回
array(
1 => "value1",
5 => "value5",
12 => "value12",
"fields" => array(
"key" => "value",
),
)
Now the problem occurs - $request->get("fields")
returns null. 现在出现了问题-
$request->get("fields")
返回null。
$request->all()
returns with fields. $request->all()
返回字段。
$request->only(["fields"])
returns array with fields. $request->only(["fields"])
返回带有字段的数组。
$request->exists("fields")
returns true. $request->exists("fields")
返回true。
Why is it so? 为什么会这样呢?
EDIT 编辑
Adding the new field inside the custom request class: 在自定义请求类中添加新字段:
public function getValidatorInstance()
{
$validator = parent::getValidatorInstance();
$validator->after(function() use ($validator, $event)
{
$this->merge(["fields" => ["key" => "value"]]);
}
return $validator;
}
$request->all()
should return all data submitted through the request. $request->all()
应该返回通过请求提交的所有数据。 Behaving as it should. 表现应有的表现。
$request->only(["fields"])
is getting the fields
key from the request and casting it to an array due to the []
. $request->only(["fields"])
正在从请求中获取fields
键,并由于[]
而将其强制转换为数组。 Normal behavior 正常行为
$request->exists("fields")
is just checking if that key exists in the request data. $request->exists("fields")
只是检查该键是否存在于请求数据中。 Normal behavior 正常行为
Looking into Illuminate\\Http\\Request
, I do not see a get()
method. 查看
Illuminate\\Http\\Request
,我没有看到get()
方法。 I only method I have seen used to extract input from a request is $request->input('fieldName')
. 我看到的用于从请求中提取输入的唯一方法是
$request->input('fieldName')
。 However there is a __get()
method in Illuminate\\Http\\Request
that seems to work. 但是,
Illuminate\\Http\\Request
中有一个__get()
方法似乎有效。 I would stick with the input()
method since it is more explicit. 我会坚持使用
input()
方法,因为它更加明确。
I think you may have a simple scoping issue, and $this
isn't available in your validator's after
closure: 我认为您可能有一个简单的范围问题,并且
$this
after
关闭after
的验证器中不可用:
$validator->after(function() use ($validator, $event, $this)
{
$this->merge(["fields" => ["key" => "value"]]);
}
If you're using PHP 5.3 or below the above won't work, you will need to capture a reference to $this
in the parent scope: 如果您使用的是PHP 5.3或更低版本,则无法使用上述代码,则需要在父范围中捕获对
$this
的引用:
$self = $this;
$validator->after(function() use ($validator, $event, $self)
{
$self->merge(["fields" => ["key" => "value"]]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.