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:
Gate
to define superadmincan()
and $user->can()
$user->hasPermissionTo()
<--------- this is what i want to knowThanks
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;
}
}