Error with relationship - Laravel

Asked

Viewed 38 times

0

Guys, I’m with 2 related tables and I want to show you 1 dice that has a just "pulling" this relationship.

tables:

Users:

inserir a descrição da imagem aqui

Permissions:

inserir a descrição da imagem aqui

Table that will list:

inserir a descrição da imagem aqui

Code:

@foreach(App\User::all() as $user)
                              <tr>
                                <td>{{$user->id}}</td>
                                <td>{{$user->name}}</td>
                                <td>{{$user->permission->name}}</td>
                                <td>{{$user->email}}</td>
                              </tr>
                              @endforeach

Model "User":

public function permission()
{
    return $this->hasOne('App\Permission', 'id', 'role');
}

error:

inserir a descrição da imagem aqui

  • What is the foreign permission key? id or name?

  • id is the permission key, but I want to show the name

  • The name is of the user?

  • name is of the permission I want it to appear, but also name in User

  • You can see in the annex I put to the question

  • Try to put it like this: {{ $user->permission->name }}

  • error, I will put in the publication

  • The two users have scrolls registered for it? you can try to encompass in an optional method, for example {{ optional($user->permission)->name }} if the user has no relation to permission, will return empty

  • yes, each has its own registered role

  • Var_dump user output

  • Try it this way {{ $user->permission[0]->name }

  • It doesn’t do that up, it’s gambiarra. I’m sorry, but it is. It has the right.

  • As it is in the controller?

  • it was no way

  • controller does not have any function

Show 10 more comments

1 answer

0


The second term of the function belongsTo() is the name of the key has that in the table users which will serve as a comparison with the table permissions.

public function permission()
{
    return $this->belongsTo('App\Permission', 'role');
}

Automatically it will compare with the column id table permissions, unless you define in the third term which column should serve as a comparison.

  • The table appeared, but the column permission without data.

  • You changed something in your view?

  • I switched function to belongsTo().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.