Reputation: 1558
I'm using Laratrust package for ACL in my application. I'm trying to edit roles (assign permissions to role) using checkbox. And want get already assigned permission checkbox state checked from database.
Code in RoleController.php
public function edit($id)
{
$role = Role::where('id', $id)->with('permissions')->first();
$permissions = Permission::all();
return view('admin.manage.roles.edit')->withRole($role)->withPermissions($permissions);
}
Below is the code what I have tried:
@foreach($permissions as $permission)
<div class="checkbox checkbox-styled">
<label>
<input type="checkbox" name="permissions[]" value="{{$permission->id}}"
{{ $role->permissions->pluck('id') == $permission->id ? 'checked' : '' }}
>
<span>{{$permission->display_name}} <em>({{$permission->description}})</em></span>
</label>
</div>
@endforeach
The code is throwing error
Object of class Illuminate\Support\Collection could not be converted to int
I had tried:
{{ $role->permissions->id == $permission->id ? 'checked' : '' }}
This throws error:
Property [id] does not exist on this collection instance
When I do {{dd($role->permissions)}}
: The following output was given:
I would be very thankful if anyone could point-out mistake I'm doing here.
Upvotes: 2
Views: 14770
Reputation: 56
Another short method.
<input type="checkbox" name="permissions[]" value="{{ $permission->id }}"
{{ $role->permissions->contains($permission->id) ? 'checked' : '' }}>
Upvotes: 0
Reputation: 11
Easiest way to do is to check in collection using contain
@if($role->permissions->contains($permission->id)) checked=checked @endif
<input type="checkbox" name="permissions[]" value="{{$permission->id}}"
{{ @if($role->permissions->contains($permission->id)) checked=checked @endif }}
>
Upvotes: 1
Reputation: 3541
Your code will not work because you are trying to compare array with a string, which is impossible. you can use php in_array
function to check whether your permission exist for the current permission or not
I think you are trying to check all the permission which already exist for the specific roles. correct me if i am wrong.
Try this
<input type="checkbox" name="permissions[]" value="{{$permission->id}}"
@if($role->permissions) @if(in_array($permission->id, $role->permissions->pluck('id')) checked @endif @endif>
Hope this will help :)
Upvotes: 3