如何在Laravel中从多对多关系中获取数据

时间:2018-12-10 08:47:26

标签: php laravel many-to-many

我想将所有用户和相关角色检索到laravel中的一个表。但是我无法继续,因为我遇到了错误

这是我的控制器功能

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

这是我的用户模型的角色功能

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

这是我的角色类的用户功能

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

这是我的数据表

@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

请帮助我解决这个问题。

2 个答案:

答案 0 :(得分:2)

更改您的控制器代码

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

然后,从更改刀片服务器代码

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

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

答案 1 :(得分:1)

编辑此行:

return view('users', campact($users));

收件人:

return view('users', compact('users'));