Ruka Xing
Ruka Xing

Reputation: 642

Laravel 5.3 foreach 2 collections from 2 diffrent models

View

@foreach ($duplicates as $duplicate)
  <tr>
     <td style="text-align: center;">{{ $duplicate->topic->id }}</td>
     <td style="text-align: center;">{{ $duplicate->topic->title }}</td>
     <td style="text-align: center;">{{ $duplicate->total }}</td>
     @foreach($choices as $choice)
     <td style="text-align: center;">{{ $choice->question_number }}</td>
     <td><a class="btn btn-default" href="choices/{{ $choice->id }}/edit">Шинэчлэх</a></td>
     @endforeach
  </tr>
@endforeach

I want result like

@foreach ($duplicates as $duplicate)
   <tr>
      <td style="text-align: center;">{{ $duplicate->topic->id }}</td>
      <td style="text-align: center;">{{ $duplicate->topic->title }}</td>
      <td style="text-align: center;">{{ $duplicate->total }}</td>
      <td style="text-align: center;">{{ $choice->question_number }}</td>
      <td><a class="btn btn-default" href="choices/{{ $choice->id }}/edit">Шинэчлэх</a></td>
   </tr>
@endforeach

i want result like @foreach(duplicates as $duplicate, $choices as $choice) this. but i know i will get error. but how?

Upvotes: 1

Views: 98

Answers (2)

Cong LB
Cong LB

Reputation: 108

have you tried using Eloquent: Relationships? I dont have pc right here so I have not genarated a example to test this, but I hope it would be some useful.

laravel eloquent relationships docs

Upvotes: 1

OneLiner
OneLiner

Reputation: 611

You can try

@foreach (array_combine($duplicates->toArray(), $choices->toArray()) as $duplicate => $choice){
    // Do some stuff
@endforeach

If Laravel's blade syntax doesn't allow for this then you can always generate the html in pure PHP and forgo the blade syntax. This is all assuming that $duplicates and $choices are both query objects, which from your code they seem to be.

Upvotes: 1

Related Questions