Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined property in model

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;
} 
like image 537
yooouuri Avatar asked Mar 11 '23 00:03

yooouuri


1 Answers

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;

like image 55
Avik Aghajanyan Avatar answered Mar 19 '23 11:03

Avik Aghajanyan