John Davidson

php - Laravel foreach loop with checkboxes

0 comments
Message:


I have below two arrays


$vendor_permissions = [1,2,3,4]
$assigned_vendor_permissions = [1,3]

I have a table with checkboxes for all permissions in one row.


Now, I want to check only those checkbox which has $assigned_vendor_permissions, means, in this case, there are 4 checkboxes as per $vendor_permissions and 2 must be checked as permissions $assigned_vendor_permissions [1,3] assigned to the user.


I tried with the below loop, but I could not get success, as it repeats checkboxes
more than 4 times,


@foreach ( $vendor_permissions as $vendor_permission )             
@if ($assigned_vendor_permissions->isNotEmpty())
@foreach ( $assigned_vendor_permissions as $rolem )
<td style="width: 15%"><label class="checkbox"><input type="checkbox" name="permissions[]" id="{{ $vendor_permission->name }}"
{{ $vendor_permission->id == $rolem->id ? 'checked="checked"' : '' }} value="{{ $vendor_permission->id }}""><span></span></label></td>
@endforeach
@else
<td style="width: 15%"><label class="checkbox"><input type="checkbox" name="permissions[]" id="{{ $vendor_permission->name }}"
value="{{ $vendor_permission->id }}""><span></span></label></td>
@endif
@endforeach

How can I get these checkboxes checked and unchecked based on the array?


Output of dd($assigned_vendor_permissions);


array:2 [▼
0 => array:6 [▶
"id" => 1
"name" => "vendor_create"
"guard_name" => "web"
"created_at" => null
"updated_at" => null
"pivot" => array:2 [▶
"role_id" => 2
"permission_id" => 1
]
]
1 => array:6 [▶
"id" => 2
"name" => "vendor_read"
"guard_name" => "web"
"created_at" => null
"updated_at" => null
"pivot" => array:2 [▶
"role_id" => 2
"permission_id" => 2
]
]
]


My Answer:
You can simplify your loop by checking if the current $vendor_permission is in the $assigned_vendor_permissions array. Here's an updated version of your loop:

php
@foreach ($vendor_permissions as $vendor_permission)



@endforeach


In this updated loop, we use the `in_array` function to check if the current $vendor_permission is in the array of 'id' values from $assigned_vendor_permissions. If it is, the checkbox will be checked.

Rate this post

5 of 5 based on 1488 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us