How to access belongsTo and hasOne in the view? - Relationship 1 - 1 bidirectional

Asked

Viewed 131 times

0

I am with project Laravel 6.0 and have the entity User and address, where user has 1 address, as well as an address belongs to 1 user (bidirectional).

The problem is that list all addresses and in the list have the column of the user name, even with you, but it does not seem to me the best way, so I would like to help to know the best way. Follows development:

Model User and Adress:

User

public function address(){
    return $this->hasOne(Adress::class, 'user', 'id');
}

Adress

public function user(){
    return $this->belongsTo(User::class, 'user', 'id');
}

Web.php:: Route:

 Route::get('enderecos', 'AdressController@index')->name('adress.list');

Adresscontroller:: Index method to list

public function index()
{
    $users = User::all();
    $adresses = $this->adress->paginate(5);
    return view('adress.index', compact('adresses', 'users'));
}

index.blade.php:: View listing

    <table class="table" id="formCad">
        <tr>
            <td>Id</td>
            <td>Rua</td>
            <td>Numero</td>
            <td>Cidade</td>
            <td>Estado</td>
            <td>Usuário</td>
        </tr>

        @foreach($adresses as $adress)
            <tr>
                <td>{{$adress->id}}</td>
                <td>
                    <a href="{{route('adress.details', ['adress'=>$adress])}}">
                        {{$adress->street}}
                    </a>
                </td>
                <td>{{$adress->number}}</td>
                <td>{{$adress->city}}</td>
                <td>{{$adress->state}}</td>
                <td>
                    @foreach($users as $user)
                        @if($user->id == $adress->user)
                            {{$user->name}}
                        @endif
                    @endforeach
                </td>
            </tr>
        @endforeach
    </table>

This is the best way below? Could you explain me or tips?

<td>
    @foreach($users as $user)
         @if($user->id == $adress->user)
              {{$user->name}}
          @endif
    @endforeach
</td>

Thank you!

  • I need help with this problem and not destructive criticism... HELP

2 answers

1


You don’t need to loop the user array to know which user’s address is. The relationship you created should bring this information.

The problem here is that you created in the database the column user, and used that same name in the relationship.

Try calling the relation with another name, example:

Address.php

public function addressUser(){
    return $this->belongsTo(User::class, 'user', 'id');
}

That way you’ll have the field user that comes from the bank and the field addressUser which will be a mapped relationship to the user object.

In doing so, try to access it this way:

@foreach($adresses as $adress)
    <tr>
        <td>{{$adress->id}}</td>
        <td>
            <a href="{{route('adress.details', ['adress'=>$adress])}}">
                {{$adress->street}}
            </a>
        </td>
        <td>{{$adress->number}}</td>
        <td>{{$adress->city}}</td>
        <td>{{$adress->state}}</td>
        <td>
            {{$adress->addressUser->name}}
        </td>
    </tr>
@endforeach

For the next relationships, I recommend using the nomenclature that Laravel itself indicates, which is {nome_tabela}_id, that is, instead of in the table address you have a field user, use a field called user_id.
This way Laravel can even do automatic mapping on BelongsTo, then you’d just need to use $this->belongsTo(User::class);. And it gets better too because you can name the relationship user, because it will not conflict with the original fields.

  • Hello, Phiter, it worked perfectly! The problem this whole time was the name of the method, our :o... Thank you so much for the feedback and tips!!!! :)

  • 1

    @Rafaelblum if it helped you remember to accept the answer as the correct one!

  • Yes :) Thanks again! I just don’t know why there is a crowd there that negative the question... I sought to study and content, but I know return, so I searched here in the community. I’m glad there are people who help people like you with difficulty... thank you!

  • 1

    @Rafaelblum the Stackoverflow community is kind of toxic, it always has been, and they’re taking steps to improve it lately, but it’s still a big problem. They are not good with beginners, and they do not help when the question is not clear, they would rather just close than ask to improve.

  • Well so... I am new in the community and have always had this perception... the purpose is to help and see in a constructive way everything and always tried to put clearly, even to help the person to know how it works and then help me :). Thank you, Brow!!! :)

1

You don’t need to call both relationships, just call one

I would do so:

public function index(){
$users = User::with(['address'])->->paginate(5);
return view('adress.index', ['users' => $users]);

}

on the Index:

@foreach($users as $user)
<tr>
    <td>{{$adress->id}}</td>
    <td>
        <a href="{{route('adress.details', ['adress'=>$user->adress])}}">
            {{$user->adress->street}}
        </a>
    </td>
    <td>{{$user->adress->number}}</td>
    <td>{{$user->$adress->city}}</td>
    <td>{{$user->$adress->state}}</td>
    <td>
        {{$user->->name}}
    </td>
</tr>
@endforeach

In case you want to do by the addresses you exchange and use the paginate by addresses and exchange the relationship...

I think funnel!

  • Thank you very much, Luiz :)! I managed doing so. I was not following the standard of Laravel documentation, so the difficulty and I know that we can also do this relationship differently from the documentation. Thank you very much!!

  • 1

    Yesterday I discovered that the relationships work even if there is a foreign key programmed in the bank, because in my approval environment the tables were not being created with Innodb, but with Myisan, and when I went to check the foreign keys were not in the bank, but the relationships worked... you’ll understand, In fact, I understood that the foreign keys are nothing more than the indexes to make the relationships faster. I’m glad I could help you!

  • Yeah, I’m still on a level start with Laravel/php, but I’m really enjoying it. The development is much faster than Java.

Browser other questions tagged

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