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

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?




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:

<input type="checkbox" name="resources[{{$sql->id}}][]" value="c">Create
<input type="checkbox" name="resources[{{$sql->id}}][]" value="r">Read

Then your PHP code could look something like this:

foreach ($request->input('resources') as $id => $resources) {
    $options[$id] = implode(',', $resources);

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.


    1 => "c,r,u,d",
    2 => "c,r,d"



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.

public function store(Request $request) {
   // get all values separated by comma
   $selectedValues = implode(",", $request->input('resources'));

  // save values in database here




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 :

foreach($_POST['resources'] as $resources){

People are also looking for solutions to the problem: php - Laravel Eloquent whereIn with where inside relationship


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.