Mathew Magante
Mathew Magante

Reputation: 1407

How to render all data in relation in laravel

I am new in this situation, I wan't to get value of "otmain_many_otline" but I don't know how to get it, I think I should put it in array cause when I use this $list->otmain_many_otline[0]->purpose I only get first data. My problem is I don't know the syntax how to render all data?

View

<table id="example1" class="table table-bordered table-hover">
 <thead>
  <th>Purpose</th>
  </thead>
  <tbody>
  @foreach($ot_list as $list)
   <tr>
    <td>        
       {{$list->otmain_many_otline[0]->purpose}}
    </td>
   </tr>
  @endforeach
  </tbody>
</table>

Model

class OTMain extends Model
{
    protected $table = 'ot_main';
    public function otmain_many_otline(){
        return $this->hasMany('App\OTline', 'ot_main_id','id');
       }

}

class OTLine extends Model
{
    protected $table = 'ot_line';
    public function otline_belong_otmain(){
          return $this->hasOne('App\OTMain', 'ot_main_id');
    }
}

Controller

 $ot_list = OTMain::whereIn('created_by', $requestor_list)
     ->with('otmain_many_otline')
     ->where('ot_status', 1)
     ->get();
 dd($ot_list);

Output:

enter image description here

Upvotes: 0

Views: 181

Answers (2)

d3jn
d3jn

Reputation: 1410

Your otmain_many_otline relation is hasMany meaning that it will return you collection of related objects. Make sure to read official documentation on them.

If you need to get first related object then use method first(). In your case:

@foreach($ot_list as $list)
    <tr>
        <td>        
            {{ $list->otmain_many_otline->first()->purpose }}
        </td>
    </tr>
@endforeach

If you need to render all related objects you can also just iterate through omain_many_otline with another @foreach:

...
<td>
    @foreach ($list->otmain_many_otline as $otline)
        <p>{{ $otline->purpose }}</p>
    @endforeach
</td>
...

Upvotes: 1

Manohar Khadka
Manohar Khadka

Reputation: 2195

You can simply do this:

@foreach($ot_list as $list)
<tr>
 <td>
    @foreach($list->otmain_many_otline as $ot) // foreach for $otmain_many_otline       
     {{$ot->purpose}} , &nbsp;
    @endforeach
 </td>
</tr>
@endforeach

Upvotes: 1

Related Questions