How to get data from table roles the views through the Auth methods in laravel?

0

I have this relationship:

In User.php:

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

in Role.php

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

Related to the role_user table:

public function up()
{
Schema::create('role_user', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('role_id')->unsigned();
    $table->integer('user_id')->unsigned();
    $table->timestamps();
});
}

I am using the basic methods of laravel that Auth gives to authenticate, register, deslogue, allows me to do everything right until I get the name of the user in the view as follows:

{{ Auth::user()->nombre }}

Now my question is, how do I get the data from the roles table through the relationship with the Auth method in the view? I'm trying something like that, but it does not work:

{{ Auth::user()->roles()->nombre }}
    
asked by Susje 26.05.2018 в 06:26
source

1 answer

1

To get the roles you have to access the property roles

{{ Auth::user()->roles }}

The function ->roles() returns the relation while the property roles ->roles returns the data.

Since the user-roles relationship is 1 to n, this will return a collection of roles.

You will have to go through the collection to paint all the roles.

@php $roles = Auth::user()->roles @endphp
@foreach($roles as $rol)
    {{ $rol->nombre }}
@endforeach
    
answered by 26.05.2018 / 11:13
source