yooouuri
yooouuri

Reputation: 2658

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;
} 

Upvotes: 4

Views: 13921

Answers (2)

Avik Aghajanyan
Avik Aghajanyan

Reputation: 1023

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;

Upvotes: 9

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

Use the relation, not property:

{{ $user->role()->name }}

Upvotes: 0

Related Questions