I tried making an authorization function roles with admin, sales, and users in it. And I make several gate rules. These are so far that I did.
App\User
public function Roles()
{
return $this->belongsToMany('App\Role');
}
public function hasAnyRoles($roles)
{
if ($this->roles()->whereIn('name', $roles)->first()) {
return true;
}
return false;
}
UsersController
public function index()
{
$users= User::all();
return view('admin.users.index')->with('users', $users);
}and the other user's role as well.
AuthServiceProvider
Gate::define('manageUsers', function($user){
return $user->hasAnyRoles(['admin, sales']);
});
routes\web
Route::namespace('Admin')->prefix('admin')->name('admin.')->middleware('can:manageUsers')->group(function(){
Route::resource('/users', 'UsersController', ['except' =>['show', 'store', 'create']]);
});
and this is the problem
->middleware('can:manageUsers')
after I put this into my route I can't access the admin.users.index.php, and I thought and I want to kick any other Users Role except admin, and sales from admin.users.index.php
but instead of what I thought, it actually kicks everyone out from admin.users.index.php
help! how to make admin and sales roles can get in into admin.users.index.php?
In your gate definition, you have
Gate::define('manageUsers', function($user){
return $user->hasAnyRoles(['admin, sales']); //array contains one value 'admin, sales' theres no role like that
});
It should be
Gate::define('manageUsers', function($user){
return $user->hasAnyRoles(['admin', 'sales']); //array listed with 2 items.
});
Since your gate check is currently checking if the user has a role called "admin, sales", the check will return false. Of course the assumption from the belongsToMany is that that your users will have many roles and each individual role like 'admin' and 'sales' are attached to the user through the belongsToMany relationship