Error when extracting data from a relationship with laravel

1

I have 2 tables users and roles , I'm trying with laravel to get the name of the role which my user owns, this is my Model of roles

class Role extends Model
{
    protected $table = 'roles';

    public function user(){

        return $this->hasMany('App\User');

    }

}

Relation Model User

public function role(){
    return $this->hasMany('App\Role', 'id');
}

I try to get the data using:

$user = \Auth::user();

echo $user->id_role->name;

If I use only:

echo $user->id_role;

brings me the data without problems, the drawback is to get the data from the role table. I throw the error

  

Trying to get property of non-object

    
asked by Edwin Aquino 17.05.2018 в 22:24
source

2 answers

1

I would need to see the definition of the tables but in principle to use the relationship you have to call the relationship and you are not doing it.

You should do

$user->role->name;

My recommendation is that you use a Many to Many relationship to do this. In fact, the example of this type of relationship in the documentation is with users and roles.

Table users
- id
- name

Table roles
- id
- name

Table role_user
- id
- role_id
- user_id

Model User

public function roles()
{
    return $this
        ->belongsToMany('App\Role');
}

Model Role

public function users()
{
    return $this
        ->belongsToMany('App\User');
}

This works for you safely

foreach ($user->roles as $role) {
    echo $role->name;
}
    
answered by 18.05.2018 / 03:01
source
1

The relationship from Role is not correct, you have this

public function role(){
   return $this->hasMany(App\Role::class);
}

When it should be:

public function role(){
   return $this->belongsTo(App\Role::class);
}

To recover the role name you just have to do something like:

$user->role->name;
    
answered by 18.05.2018 в 01:13