php - 带有转发器字段的 Laravel 表单提交中的 ErrorException 数组到字符串转换
问题描述
在我的 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 模型中进行投射的更多信息
推荐阅读
- android - 从 Firestore 中的文档中获取空值
- python - 通过 Internet 发送 UDP 数据包只能工作一半
- javascript - How to override a TypeScript UMD global type definition?
- javascript - 允许用户垂直调整块的大小并将其下方的所有内容向后/向前推
- android - 每当实现 parse:1.20.0 时,如何解决 appcompat-v7:28.0.0 上的 Gradle 兼容性问题?
- java - Android - 在 Fragment 中设置 BottomSheet 中 FAB 按钮的可见性
- spring-boot - 在 JPA 中使用 findByField 选择多个字段
- c - Posix 串行端口原始读取挂起
- javascript - Little problem with accordion-menu (hide/show)
- symfony - @UniqueEntity 不强制执行多字段约束