In my Laravel application, I have the following form to submit data:
JavaScript
x
{!! 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() !!}
This is my create.blade.php
And my controller looks like this:
JavaScript
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.');
}
}
Now the problem is, whenever I tried to submit the data, it gives me an error saying
ErrorException Array to string conversion
test_type
and test_result
fields are repeaters. Due to that, I’ve used those field names as test_type[]
and test_result[]
.
Advertisement
Answer
As you’re trying to save an array in your database, you need to define a text or json column in your database and cast the field to one of array, json or collection types.
Define cast in TestResult model:
JavaScript
TestResult
{
protected $casts = [
'test_type' => 'array',
'test_result' => 'array',
];
}
Learn more about casting in laravel models from here