E
E
Eugene2020-01-24 01:14:40
Laravel
Eugene, 2020-01-24 01:14:40

How to group checkbox by their entities?

Hello.
There is a table with permissions

Schema::create('permissions', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('entity');
});

I display them for each role in this way
<div class="form-group">
                        <div class="col-lg-10">
                          @foreach($permissions as $permission)
                            <input {{ in_array($permission->id, $rolePermissions) ? "checked" : null }} name="permissions[]" value="{{ $permission->id}}"  type="checkbox" />{{ $permission->name}}</label>
                          @endforeach
                        </div>
                     </div>

4 permissions belong to the same entity. And I want to display them in the form (Entity -> 4 checkbox)
This is how everything looks now:
5e2a1a66e185b925976910.png
It seems like a simple task, but it doesn’t occur to me how to do it

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex Wells, 2020-01-24
@Eugene70

->groupBy('entity')

D
Denis Kainazarov, 2020-01-24
@iit

The easiest option is to loop through them

$permissions =  Permission::all();

$permissionEntity = [];
foreach($permissions as $permission){
    if(!isset($permissionEntity[$permission->entity]){ 
            $permissionEntity[$permission->entity] = [];
    }
    $permissionEntity[$permission->entity][] = $permission;
}

@foreach($permissionEntity as $entity => $permission)
    <h4>{{ $entity }}</h4>
    <div class="form-group">
        <div class="col-lg-10">
            <input {{ in_array($permission->id, $rolePermissions) ? "checked" : null }} name="permissions[]" value="{{   $permission->id}}"  type="checkbox" />{{ $permission->name}}
         </div>
    </div>
@endforeach

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question