我有一个我在larvel -5中创建的表单。这个表单包含输入数组。我还使用php artisan make:request ClassRequest
创建了一个请求文件。在我的请求文件中,我添加了Laravel validator()函数,我使用它在表单发布时向表单数组添加额外的字段。
然而,我似乎不能得到的形式数组更新/合并的方式,我想。
视图文件:
<input type="text" name="class[0]['location_id']" value="1">
<input type="text" name="class[1]['location_id']" value="2">
请求文件(ClassRequest.php):
<?php
namespace AppHttpRequests;
use AppHttpRequestsRequest;
use IlluminateContractsValidationValidator;
use IlluminateValidationFactory as ValidatorFactory;
use DB;
class ClassRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function validator(ValidatorFactory $factory)
{
$input = $this->get('class');
foreach($input as $key => $val)
{
$dateInString = strtotime(str_replace('/', '-', $input[$key]['date']));
$this->merge(['class' => [$key => [
'location_id' => $input[$key]['location_id'],
'location' => 'test123'
]
]]);
}
return $factory->make($this->input(), $this->rules(), $this->messages());
}
}
正如您从上面的请求文件中看到的,我试图向表单数组(location => 'test123')添加一个新的键/值对。然而,只有一个字段被发送到控制器。
有谁知道这样做的正确方法吗?
Merge 函数将给定数组合并为集合,并且数组中任何与集合中的字符串键匹配的字符串键将覆盖集合中的值。这就是为什么你只看到一个字段通过控制器发送。
foreach($input as $key => $val)
{
$this->merge(['class' => [$key => [
'location_id' => $input[$key]['location_id'],
'location' => 'test123'
]
]]);
}
'class'
键在每次迭代中被覆盖,并且只保留最后一个键。所以唯一的项是最后一项。
$input = $this->get('class');
foreach($input as $key => $val)
{
$another[$key]['location_id']=$input[$key]["'location_id'"];
$another[$key]['location']='123';
}
$myreal['class']=$another;
$this->merge($myreal);
return $factory->make($this->input(), $this->rules(), $this->messages());
如果你得到与位置id相关的错误,那么试试这个
public function validator(ValidatorFactory $factory)
{
$input = $this->get('class');
foreach($input as $key => $val)
{
foreach($input[$key] as $v){
$another[$key]['location_id']=$v;
$another[$key]['location']='124';
}
}
$myreal['class']=$another;
$this->merge($myreal);
return $factory->make($this->input(), $this->rules(), $this->messages());
}