[英]ErrorException Array to string conversion in Laravel form submission with repeater fields
在我的 Laravel 应用程序中,我有以下表单来提交数据:
{!! Form::open(array('route' => 'testresults.store','method'=>'POST')) !!}
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Test ID:</strong>
@foreach ($getTests as $object)
{!! Form::text('test_id', ''.$object->id .'', array('placeholder' => 'Test Name','class' => 'form-control','readonly')) !!}
@endforeach
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<table class="table table-bordered">
<tr>
<th>Test</th>
<th width="280px">Result</th>
</tr>
@foreach ($getTests as $key => $getTest)
@foreach (explode(',', $getTest->samp_list) as $samp_list)
<tr>
<td>
{!! Form::text('test_type[]', ''.$samp_list.'', array('placeholder' => 'Test Type','class' => 'form-control','readonly')) !!}
</td>
<td>{!! Form::text('test_result[]', null, array('placeholder' => 'Test Result','class' => 'form-control')) !!}</td>
</tr>
@endforeach
@endforeach
</table>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Test By:</strong>
{!! Form::text('test_by', ''.Auth::user()->name .'', array('placeholder' => 'Test Name','class' => 'form-control','readonly')) !!}
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
{!! Form::close() !!}
这是我的create.blade.php
我的控制器看起来像这样:
public function store(Request $request)
{
try{
request()->validate([
'test_id' => 'required',
'test_type' => 'required',
'test_result' => 'required',
'test_by' => 'required',
]);
TestResult::create($request->all());
return redirect()->route('testresults.index')
->with('success','Test Type created successfully.');
}
catch(Exception $e){
return redirect()->route('testresults.create')
->with('failed','An error has been occured.');
}
}
现在的问题是,每当我尝试提交数据时,它都会给我一个错误提示
ErrorException 数组到字符串的转换
test_type
和test_result
字段是中继器。 因此,我将这些字段名称用作test_type[]
和test_result[]
。
当您尝试在数据库中保存数组时,您需要在数据库中定义一个 text 或 json 列,并将该字段转换为数组、json 或集合类型之一。
在TestResult模型中定义强制转换:
TestResult
{
protected $casts = [
'test_type' => 'array',
'test_result' => 'array',
];
}
从这里了解有关在 Laravel 模型中进行转换的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.