Home > Enterprise >  How can i loop foreach in foreach from 2 tables
How can i loop foreach in foreach from 2 tables

Time:04-26

I have addresses and i have users

I want to loop all the users name and in the other rows data from addresses like street and so.

User model

   public function address(){
        return $this->belongsTo(Address::class);
    }

Address model

 public function users(){
        return $this->hasMany(User::class);
    }

what i tried

 @foreach($users as $user)

            @foreach($user->addresses as $address)

                <tr>
                    <td>{{$address->id}}</td>


                    <td><a href="{{route('addresses.edit', $user->id)}}">{{$user->name}}</a></td>

                  
                    <td>{{$address->address}}</td>

                    <td>{{$address->city}}</td>

                    <td>{{$address->postal_code}}</td>

                </tr>

            @endforeach
            @endforeach

CodePudding user response:

I would recommend two solutions:

  1. if the relationship is working try to use :

    @foreach ($users as $user)

         <tr>
    
             <td>{{$user->id}}</td>
    
             <td>{{$user->name}}</td>
    
     <!-- Use a relationship (e.g., address) to get additional data -->
             <td>{{$user->address->address}}</td>
         </tr>
     @endforeach
    
  2. orjust use (join) in your controller to link the two tables

here is an examples how to apply that: https://www.tutsmake.com/laravel-8-joins-example-tutorial/

CodePudding user response:

You've got typo, try this:

@foreach($users as $user)

            @foreach($user->address as $address)

                <tr>
                    <td>{{$address->id}}</td>


                    <td><a href="{{route('addresses.edit', $user->id)}}">{{$user->name}}</a></td>

                  
                    <td>{{$address->address}}</td>

                    <td>{{$address->city}}</td>

                    <td>{{$address->postal_code}}</td>

                </tr>

            @endforeach
            @endforeach

Your relation in User model is "address", but you are using "addresses" in blade. Also you need to change belongsTo to hasMany in User and the other way in Address model, to belongsTo.

public function address(){
        return $this->hasMany(Address::class);
    }

 public function users(){
        return $this->belongsTo(User::class);
    }
  • Related