1

I have a problem with spatie/laravel-permissions...

I use Gate in AuthServiceProvider.php to define Superadmin (can bypass all permissions without register it to the role)...

It is working perfectly with can('the-permission') helper.

But it is not working with Auth::user()->hasPermissionTo('the-permission')...

.

.

Below is my code:

.

In AuthServiceProvider.php:

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

    Gate::before(function ($user, $ability) {
        $superadmin_rolename = 'Superadmin';
        $guard_name = 'web-admin';
        return $user->hasRole($superadmin_rolename , $guard_name ) ? true : null;
    });
}

.

.

In Blade:

@can('add products')
    <button type="submit">Add Product</button>
@endcan

// this will work perfectly, the button will be shown

.

.

In Controller:

public function addProduct()
{
    $admin = Auth::guard('web-admin')->user();

    if($admin->hasPermissionTo('add products')) return true;

    return false;
}

// this is not working (it return false)... i dont know why.... it should return true....

so, as what I show to you above:

  • I use Gate to define superadmin
  • the superadmin should grant all access
  • it is working perfectly with can() and $user->can()
  • but it is not working with $user->hasPermissionTo() <--------- this is what i want to know

Thanks

apokryfos
  • 38,771
  • 9
  • 70
  • 114
Syamsoul Azrien
  • 2,534
  • 4
  • 32
  • 55
  • 2
    `hasPermissionTo` only checks the database, it does not run `gate::before`, [this](https://github.com/spatie/laravel-permission/issues/1062#issuecomment-472953165) should answer your question. – Remul Sep 25 '19 at 08:51
  • thanks for sharing the answer.... – Syamsoul Azrien Sep 25 '19 at 08:59

1 Answers1

1

Based on @Remul's comment, I found that only can() or $user->can() will work perfectly with Gate::before....

So, how if I want to use another method like $user->hasAnyPermission or $user->hasAllPermissions ?

.

This is what I do...I decided to create a custom method in the Admin model..

<?php

namespace Model;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class Admin extends Authenticatable
{
    use HasRoles;

    protected $guard_name = "web-admin";

    protected $fillable = ['name', 'email', 'password'];

    public function canAny(array $permissions)
    {
        foreach($permissions as $e){
            if($this->can($e)) return true;
        }

        return false;
    }

    public function canAll(array $permissions)
    {
        foreach($permissions as $e){
            if(!$this->can($e)) return false;
        }

        return true;
    }
}
Syamsoul Azrien
  • 2,534
  • 4
  • 32
  • 55
  • I wrote the two functions directly in my User-Modal. I took function names (hasAnyPermission & hasAllPermissions) from Spatie and that works. – Norman Huth Nov 11 '19 at 20:45