I am trying to insert data into database. But i don’t know how to insert multi select data into the mysql database.
<div class="form-group"> <select name="languages[]" class="select2 form-control" multiple="multiple "required> <option selected>English</option> <option VALUE="french">French</option> <option VALUE="german">German</option> <option VALUE="spanish">Spanish</option> <option VALUE="turkish">Turkish</option> <option VALUE="italian">Italian</option> </select> </div> </div>
Controller
public function store(Request $request) { User::create($request->all()); return redirect()->back(); }
return error
ErrorException Array to string conversion
Advertisement
Answer
$request->languges
is an array, and you can’t save an array into a VARCHAR() field.
In your name attribute languages[]
will make an array, not string. While name attribute languages
make a string
If you have an array, then you need a foreach loop in your controller.
With select2 you need to make an array while sending multiple data.
The table property needs to be a string not an array, So let’s convert array to string :
With Server-side
With foreach :
public function store(Request $request) { $data = $request->all(); $x = NULL; foreach($request->languages as $key => $value) { $x .= $value .", "; } $data['languages'] = $x; User::create($data); return redirect()->back(); }
Or, with Implode :
public function store(Request $request) { $data = $request->all(); $data['languages'] = implode(',', $request->languages); User::create($data); return redirect()->back(); }
With Client-side, jQuery
:
Your title says “send selected values of select box to PHP as string”. You would do that in JS by catching the submit event of the form and using .join()
to change the value of that field.
$('#formid').on('submit', function(){ $('#e1').val($('#e1').val().join(',')); });
Your form (not given) would need an id <form id="formid" ...>