php - Unable to access values from multiple html checkboxes
I am trying to save the values from html checkboxes in a MySQL database table but I am not doing it right. I need your suggestions here.
This is my html
@foreach($sql as $sql)
<div >
<label for="">{{$sql->name}}</label>
<div >
<input type="hidden" name="resource[]" value="{{$sql->id}}">
<input type="checkbox" name="resources[]" value="c">Create
<input type="checkbox" name="resources[]" value="r">Read
<input type="checkbox" name="resources[]" value="u">Update
<input type="checkbox" name="resources[]" value="d">Delete
</div>
</div>
@endforeach
This is my controller where I am trying to save into a DB table
public function store(Request $request) {
foreach ($request->resource as $resource) {
# code...
foreach ($request->resources as $resources) {
$res[] = $resources;
$options = implode(',', $res); // Get selected options
$resource = $resource; // Get value of the resource
}
}
}
This does not work as it only shows just one 'selected checkbox field'. Please what am I doing wrong?
Answer
Solution:
Looking at your HTML code, it appears you're going to be looping over possibly more than one SQL statement to make the checkboxes. The server won't be able to tell these apart. You should change your checkbox names to be more like:
Then your PHP code could look something like this:
Each SQL statement will be in the $options array keyed by the SQL id. The array value will be the checked checkboxes values separated by a comma.
Answer
Solution:
If you are trying to save the selected values separated by comma, for ex: if user has selected by c and d, then you are saving in database as c,d ?. if so then you can get all selected values in single line.
Answer
Solution:
remember the your checkbox is an array ! for your understating better what sent to your controller just write
to see what arriving exactly after that write it in your framework method like :