I had a table form where I will add multiple users in table and it has checkboxes. My problem is on the checkboxes.
User 1: ✓ Add, ✓ Edit, ✓ Delete
User 2: ✓ Add, Edit, Delete
Expected Output in Database
Full Name | Permissions
John Doe | ["Add", "Edit", "Delete"]
Jane Doe | ["Add"]
What is inserted in the DB
Full Name | Permissions
John Doe | "Add"
Jane Doe | "Edit"
blade html
<button type="button" id="addUser">Add</button>
<table id="userTable">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Add</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JS Code
$("#addUser").click(function () {
t.row.add(['',
'<input type="text" name="fullname[]">',
'<input type="checkbox" name="permissions[]" value="Add" data-parsley-multiple="status">',
'<input type="checkbox" name="permissions[]" value="Edit" data-parsley-multiple="status">',
'<input type="checkbox" name="permissions[]" value="Delete" data-parsley-multiple="status">',
]).draw(false);
});
Controller
public function store(Request $request)
{
foreach($request->fullname as $key=>$insert)
{
$user = [
'fullname' => $request->fullname[$key],
'permissions' => json_encode($request->permissions[$key]),
];
DB::table('users')->insert($user);
}
}
In my code, $request->permissions[$key]
is only getting 1 value per permission. How can I get all the checked value of permission in one user row and to be inserted for that user.
CodePudding user response:
Add indexes to your input names, so they are grouped per user:
$("#addUser").click(function () {
var index = $(".user-name-field").length;
t.row.add(['',
'<input type="text" name="fullname[' index ']">',
'<input type="checkbox" name="permissions[' index '][]" value="Add" data-parsley-multiple="status">',
'<input type="checkbox" name="permissions[' index '][]" value="Edit" data-parsley-multiple="status">',
'<input type="checkbox" name="permissions[' index '][]" value="Delete" data-parsley-multiple="status">',
]).draw(false);
});
In this case i've added a class to the user name field, count these fields to create the index