Laravel 5.5 - Check checkbox if role has permission

3.9k views Asked by At

I have the following code that works with the Form Collective package, however this isn't working right now as the package hasn't been updated for 5.5. I am also using Spatie's Laravel Permission package

The code I have is

@foreach ($permissions as $permission)

    {{Form::checkbox('permissions[]',  $permission->id, $role->permissions ) }}
    {{Form::label($permission->name, ucfirst($permission->name)) }}<br>

@endforeach

Which I believe is just looping through the permissions and if the permission belongs to the current role check the box.

How can I achieve this without using the package?

I have currently tried

@foreach ($permissions as $permission)

    <div class="checkbox">
        <label>
            {{ ucfirst($permission->name) }}
        </label>
        <input type="checkbox" name="permissions[]" value="{{ $permission->id }}">
        <br>
    </div>

@endforeach

But I'm not sure how to attach the checked attribute based on whether the role has a permission in the list.

2

There are 2 answers

5
Desh901 On BEST ANSWER

Just add the checked attribute to the checkbox HTML:

<input type="checkbox" name="permissions[]" value="{{ $permission->id }}" checked>

if you need to set it upon a condition use the following code:

<input type="checkbox" name="permissions[]" value="{{ $permission->id }}" @if(/* some condition */) checked @endif>

EDIT

Since i didn't understand the question before i'll add some details.

Assuming that your Role model has a collection of attached permissions and it is stored in the attribute $role->permissions you could do

<input type="checkbox" name="permissions[]" value="{{ $permission->id }}" @if($role->permissions->contains($permission)) checked @endif>

That way you can check if your role has the permission with id $permission->id.

7
Sreejith BS On

Try this:

@foreach ($permissions as $permission)

    <div class="checkbox">
        <label>
            {{ ucfirst($permission->name) }}
        </label>
        <input type="checkbox" name="permissions[]" value="{{ $permission->id }} {{($role->permissions == $permission->id) ? 'checked' : ''}}">
        <br>
    </div>

@endforeach