These are always tricky but make sure the role you create Operator is the same in that database and in your code. Running things in phpunit makes them case sensitive evven though they aren't normly.
It's all correct for what i see, there is something wrong when i check with the can() method because he have the permission to "view_changes" but the can method won't pick it up...
Is it possible that the policies will be loaded after running the test in test but in Tinker they will be loaded first?
class User extends Authenticatable
{
use Notifiable, HasRoles;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function isAdmin(){
return $this->hasRole('Admin');
}
public function isOperator(){
return $this->hasRole('Operator');
}
}
HasRoles Trait
<?php
namespace App;
trait HasRoles
{
/**
* A user may have multiple roles.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function roles()
{
return $this->belongsToMany(Role::class);
}
/**
* Assign the given role to the user. If it's Role class it will be called recursively
*
* @param string $role
* @return mixed
*/
public function assignRole($role)
{
if (is_string($role)) {
return $this->roles()->save(
Role::whereName($role)->firstOrFail()
);
}
return $this->assignRole($role->name);
}
public function removeRole($role){
if (is_string($role)) {
return $this->roles()->detach(
Role::whereName($role)->firstOrFail()
);
}
return $this->removeRole($role->name);
}
/**
* Determine if the user has the given role. If it's Role class it will be called recursively
*
* @param mixed $role
* @return boolean
*/
public function hasRole($role)
{
if (is_string($role)) {
return $this->roles->contains('name', $role);
}
if (is_array($role)) {
foreach ($role as $r) {
if ($this->hasRole($r)) {
return true;
}
}
return false;
}
if (isset($role->name)) {
return $this->hasRole($role->name);
}
return !!$role->intersect($this->roles)->count();
}
/**
* Determine if the user may perform the given permission.
*
*
* @param Permission $permission
* @return boolean
*/
public function hasPermission(Permission $permission)
{
return $this->hasRole($permission->roles);
}
}