我有一个在 Laravel-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 App\Http\Requests;
use App\Http\Requests\Request;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\Factory 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')。但是,只有 1 个字段被发布到 Controller 。
有谁知道这样做的正确方法吗?
最佳答案
Merge 函数将给定数组合并到集合中,并且数组中与集合中的字符串键匹配的任何字符串键都将覆盖 集合中的值。这就是为什么您只看到 1 个字段发布到 Controller 的原因。
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());
}
关于php - Laravel-5 合并多级表单数组验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31615181/