首页 文章

如何从laravel中的多对多关系中获取数据

提问于
浏览
0

我想将所有用户和相关角色检索到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 回答

  • 1

    更改您的控制器代码

    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
    
  • 2

    编辑此行:

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

    至:

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

相关问题