Saturday, March 11, 2017

Larave : How to get data from many to many relationship

I have 3 tables which are user->id, name,password, roles->id,role, role_user->role_id, user_id

Now if I want to show the associated data in view page means role related to user ..How i do it in view? means I want to show if the user has role it will be checked otherwise it will be unchecked

Here is my controller :

$users = User::all();
$roles = Role::all();
return view("Permission::assign_role",compact('users','roles'));

View page

<table class="table">
                        <thead>
                          <tr>
                            <th>SL No</th>
                            <th>Name</th>
                            <th>Role</th>
                          </tr>
                        </thead>
                         <tbody>
                                <?php $i=1; ?>
                                @foreach($users->roles() as $row)                                   
                                    <tr>
                                        <td></td>
                                        <td></td>                                                                  
                                        <td> <input type="checkbox" name="role_id" checked> $role->role</td>
                                    </tr>

                                    <?php $i++; ?>

                                @endforeach
                        </tbody>
                      </table>



via User57

Advertisement