dongxiaowei_1234 2018-04-27 20:19 采纳率: 0%
浏览 68

Laravel 5.6注册用户角色

Hello i was following this tutorial

https://www.5balloons.info/user-role-based-authentication-and-access-control-in-laravel/#comment-1889

i done everything ok and add some rules, a custom error page, and only admin can register new users. in the /admin view i can see all users register and the admin can delete this users.

i need two more roles, for users to see especific views, and i’m trying define the role in the register form so the admin can define who can see the a specific page. one role for executive user and one for premium user.

i was able to do that, but only by adding the relation in the database role_user table

any idea how to get this done by the register form? without entering in the database table

  • 写回答

1条回答 默认 最新

  • doubingjian2006 2018-04-27 21:41
    关注

    I am going to assume you're using a Blade template. Use the following to add a drop down for the Role select.

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

    You'll need to provide your currently available Roles, from your Role Model (ha), to the view. This can be done in your controller when rendering the view.

    // Part of your controller
    $roles = Role::all();
    return view('your-view', [ 'roles' => $roles ]);
    

    The key part here is return view('your-view', [ 'roles' => $roles ]). The second parameter in the view function is data to be passed to the view itself. See the Blade docs for more info.

    When you submit your form you can "attach" the role to your user model after it has been saved.

    $user = new User();
    // Assign user info here
    $user->save();
    $user->roles()->attach($request->role);
    
    • ->roles() is the model that belongs to User that we want to attach to.
    • ->attach($request->role) - $request->role is the ID of the Role we want to attach to the newly created User.

    You can read more in the docs about attaching and assigning various relationships to others.

    评论

报告相同问题?

悬赏问题

  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因