doudoulb1234 2018-02-05 16:59
浏览 218
已采纳

现在我已经成功设置了users-role_user-roles表并在它们之间建立了连接,我如何在Laravel中使用这些角色

Currently, I have seeded 1 user with the role of admin, and every new user who registers will be assigned a role of user. The roles are in a table called roles, the users are in a table called users and the connection between these 2 is in a table called role_user. Now I can't exactly figure out how to, for example, change my header to include admin menu if the logged user is an admin.

Header.blade.php

<section class="header">
    <div class="wrapper">
        <nav class="navigation">
            <ul>
                <li><a href="{{ route('home') }}">Images</a></li>
                @auth
                <li><a href="{{ route('upload') }}">Upload</a></li>
                <li class='logOut'><a href="{{ route('logout') }}">Logout</a></li>
                @endauth
                @guest
                <li class="signUp">Sign Up</li>
                <li class="logIn">Log In</li>
                @endguest
            </ul>
        </nav>
    </div>
</section>

Role.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    public function users(){
        return $this->belongsToMany('App\User');
    }
}

User.php

<?php

namespace App;

use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;


class User extends Model implements Authenticatable
{
    use \Illuminate\Auth\Authenticatable;
    public function images(){

        return $this->hasMany('App\Image');
    }

    public function roles(){
        return $this->belongsToMany('App\Role');
    }
}

Database tables

Table - users
Columns - id, username, password

Table - roles
Columns - id, name, description

Table - role_user
Columns - id, user_id, role_id
  • 写回答

1条回答 默认 最新

  • dongxuan1314 2018-02-05 19:04
    关注

    Add this function to your model for checking role

    class User extends Model implements Authenticatable
    {
        use \Illuminate\Auth\Authenticatable;
    
    
           public function roles(){
                 return $this->belongsToMany('App\Role');
           }
    
           public function hasRole($roleName){
              $result = false;
              foreach($this->roles as $role){
                  if($role->name == $roleName)
                  $result = true ;
              }
    
             return $result;
          }
    }
    

    And in your views

    @if((\Auth::check() && \Auth::user()->hasRole('admin')
        @include('admin.nav')
    @endif
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题