Skip to content
Advertisement

How to handle foreach inside foreach?

I need to follow the concept of “DRY” So I have a lot of repetition in my code. decided to make it short as I can!

The design that I need to reach is: enter image description here

my shut:

   @php
        $names = [
            'main','settings', 'admins','roles'
        ];
        $values = [
            'main_page','setting','admin','role'
        ];
    @endphp

    @foreach ($names as $name)
        <main class="role_me">
                -- {{ $name }}
            <div class="roles">
                @foreach ($values as $value)
                    <label><input type="checkbox" name="permission[]" value="{{ $value}}_read">Read</label>
                    <label><input type="checkbox" name="permission[]" value="{{ $value}}_create">Create</label>
                    <label><input type="checkbox" name="permission[]" value="{{ $value}}_update">Update</label>
                    <label><input type="checkbox" name="permission[]" value="{{ $value}}_delete">Delete</label>
                @endforeach
            </div>
        </main>
    @endforeach

The output of my code is:

enter image description here

Advertisement

Answer

Here we require two loops to display those menu and their sub menus. Try this

$action = ["Edit", "Read", "Delete", "Add"];

$categories = ["Menu", "Roles", "Users"];

for($i = 0; $i < count($categories); $i++) {
    echo $categories[$i]. "<br>";
    for($j = 0; $j < count($action); $j++) {
       echo $categories[$i]. " " .$action[$j] . "<br>";
    }
}

Output like this.

Menu
Menu Edit
Menu Read
Menu Delete
Menu Add
Roles
Roles Edit
Roles Read
Roles Delete
Roles Add
Users
Users Edit
Users Read
Users Delete
Users Add
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement