Ad

How To Get Data From Many To Many Relationship In Laravel

- 1 answer

I want to retrieve all the users and associated roles to the one table in laravel. but i couldn't continue because i'm getting error called

This is my controller function

public function index(){
    if(Auth::user()->isAdmin==1){
        $users = User::with('roles')->get();
        return view('users', campact($users));
    } else {
        abort(403, 'Unauthorized action.');
    }
}

This is my User Model's roles function

public function roles()
{
    return $this->belongsToMany(Role::class, 'role_users');
}

This is my Role Class's Users function

public function users()
{
    return $this->belongsToMany(User::class,'role_users');
}

This is my data table

@foreach ($users as $user)
    <tr>
        <td>{{ $user->id }}</td>
        <td>{{ $user->name }}</td>
        <td>{{ $user->email }}</td>
        <td>
            <form method="post">
            {{ csrf_field() }}
            <div class="form-group">                
                <select class="form-control" data-id="{{$user->id}}" id="role" name="role">
                    <option value="0">Select a Role</option>
                    @foreach ($users->roles as $role)
                    <option  value="{{ $role->id }}">{{ $role->name }}</option>
                    @endforeach
                </select>
            </div>  
            </form>          
        </td>
        <td>{{ $user->created_at }}</td>
        <td>{{ $user->updated_at }}</td>

        <td><div class="form-group">
            <form method="post" id="userActivate">
            {{ csrf_field() }}
            <label>
                <input type="checkbox" class="flat-red isActive" data-id="{{$user->id}}" @if ($user->isActive) checked @endif>
            </label>

        </form>
    </div>       
        </td>
        <td>
            <form id="userDelete" method="post" >
                {{ csrf_field() }}
                <button type="button" id="delete" data-id="{{$user->id}}" class="btn btn-block btn-danger btn-flat">Delete</button>
            </form>
        </td>
    </tr>
@endforeach

Please help me to solve this.

Ad

Answer

Change your Controller code

public function index(){
  $users = User::with('roles') // Eager loading
               ->get();
  return view('users')->with('users', $users);
}

Then, change your blade code from

@foreach ($users->roles as $role)
    <option value="{{ $role->id }}">{{ $role->name }}</option>
@endforeach

to

@if(count($user->roles) > 0)
@foreach ($user->roles as $role)
    <option value="{{ $role->id }}">{{ $role->name }}</option>
@endforeach
@endif
Ad
source: stackoverflow.com
Ad