User model:
class User extends Authenticatable
{
use Notifiable;
protected $table = 'users';
/**
* 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', 'role_id',
];
protected $appends = [
'role',
];
public function getRoleAttribute()
{
return $this->role->name;
}
/**
* User role.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function role()
{
return $this->belongsTo('App\Role');
}
}
I wan't to show the name of a role instead the role id.
But it says:
ErrorException in User.php line 38: Undefined property: App\User::$role
The roles table contains an id and name
The users table contains a role_id
Edit:
When i try return $this->role()->name;
it gives me a:
ErrorException in User.php line 38: Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name
But i check for role and that works...
/**
* Check if the user is an admin.
*
* @return bool
*/
public function isAdmin()
{
if ($this->role->name == 'admin') {
return true;
}
return false;
}
It is because you have role attribute and role relation, try to rename one of them, and it will work with return $this->role->name;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With