3

我有以下与 Form Collective 包一起使用的代码,但是由于该包尚未针对 5.5 进行更新,因此现在无法正常工作。我也在使用 Spatie 的 Laravel Permission 包

我的代码是

@foreach ($permissions as $permission)

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

@endforeach

我相信这只是循环permissions,如果permission属于当前,则role选中该框。

我怎样才能在不使用包的情况下实现这一点?

我目前已经尝试过

@foreach ($permissions as $permission)

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

@endforeach

但是我不确定如何根据角色在列表中是否具有权限来附加选中的属性。

4

2 回答 2

11

只需将checked属性添加到复选框 HTML:

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

如果您需要根据条件设置它,请使用以下代码:

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

编辑

因为在我添加一些细节之前我不明白这个问题。

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.

于 2017-08-31T11:10:53.707 回答
2

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
于 2017-08-31T11:12:11.817 回答