Nosean
5 months ago

Gates and Polieces

Posted 5 months ago by Nosean

Hello

I'm trying to build a role-based login. Have a table user, roll, and a pivottabelle user_role. User with authorization (SQL table roles, longtext field = permissions, value: {"is-admin": true}; is created.

I do this with Gates and Polieces

My AuthServiceProvider.php

     public function boot()
    {
        $this->registerPolicies();
        $this->registerAdminPolicies();

        //
    }

    public function registerAdminPolicies()
    {
        Gate::define('is-admin', function ($user) {
            return $user->hasAccess(['is-admin']);
        });
    }

My User.php


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

    public function hasAccess(array $permissions) : bool
    {
        foreach($this->roles as $role) {
            if($role->hasAccess($permissions)) {
                return true;
            }
            return false;
        }
    }

My Role.php

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

    public function hasAccess(array $permissions) : bool
    {
        foreach ($permissions as $permission) {
            if($this->hasPermission($permission))
                return true;
        }

        return false;
    }


    private function hasPermission(string $permission) : bool
    {
        return $this->permissions[$permission] ?? false;
    }

header.blade.php

<!-- LOGO UND HEADNAVBAR -->
<div class="row">
    <div class="col-xl-3">

        @auth
            {{ auth()->user()->name }} {{ auth()->user()->roles()->pluck('name') }}
        @else
            Gast
        @endauth
        @can('is-admin')
            <a href="{{ route('admin.index') }}">Admin</a>
        @endcan
    </div>
    <div class="col-xl-9 text-right">
        <a href="lang/de" id="de"><img src="{{asset('layout/images/Germany-icon.png')}}" width="30px" height="30px"></a>
        <a href="lang/en" id="en"><img src="{{asset('layout/images/United-Kingdom-icon.png')}}" width="30px" height="30x"></a>
    </div>
</div>

Login works as well!

Now I have tried in my Blade file with @can ('is-admin') to insert a link to the admin area. This is unfortunately not displayed. In the debugbar I get the following error message under the tab Gates

error
array:4 [▼
  "ability" => "is-admin"
  "result" => false
  "user" => 14
  "arguments" => "[]"
]

Therefore, in the blade between the tags @can ('is-admin') and @endcan Has somebody an idea what is the problem?

Please sign in or create an account to participate in this conversation.