Reputation: 913
I am trying to display fields from multiple table to single html table as per corresponding data in blade. But I am not getting any result
My Database Design :
District
| id
| district_name
Municipal
| id
| district_id
| Municipal_uid
| municipal_name
Area
| id
| area_name
| district_id
| municipal_id
This is what I am trying to achieve,
Area ID | Area Name | District Name | Municipal Name | municipal UID
My Model
Area:
public function districts(){
return $this->belongsTo('App\Districts');
}
public function municipals(){
return $this->belongsTo('App\Municipals');
}
Municipal:
public function district(){
return $this->belongsTo('App\Districts');
}
public function approvedlayout(){
return $this->hasMany('App\Approvedlayouts');
}
District:
public function municipal(){
return $this->hasMany('App\Municipals');
}
public function approvedlayout(){
return $this->hasMany('App\Approvedlayouts');
}
blade
<table class="table table-striped">
<thead class="text-center">
<tr>
<th>Area ID</th>
<th>Area Name</th>
<th>District Name </th>
<th>Municipal Name</th>
<th>Municipal UID</th>
</tr>
</thead>
<tbody class="list">
@foreach ($areas as $layout)
<tr>
<td>{{$layout ->id}}</td>
<td> {{ $layout-area_name }}</td>
<td> {{ $layout->districts-> district_name }}</td>
<td> </td>
<td></td>
<td></td>
</tr>
@endforeach
</tbody>
</table>
{{$areas-> links()}}
Controller
public function index()
{
$areas = Area::simplePaginate(5);
return view('admin.area.index',compact('areas'));
}
When I try to display the district name
( {{ $layout->districts-> district_name }})
I am getting error,
Trying to get property 'district_name' of non-object (View: lapp/resources/views/area/index.blade.php
Upvotes: 0
Views: 610
Reputation: 1437
You could always just used the leftJoin
an select
function on your query builder to get those results. It'll also be much faster than calling it per row.
Area::select('areas.id','areas.name', 'districts.name as district_name', 'municipals.name as municipal_name', 'municipals.id as municipal_id')
->leftJoin('districts', 'districts.id', '=', 'area.district_id')
->leftJoin('municipals', 'municipals', '=', 'area.municipal_id')
->get();
Afterwards, you can refresh the stuff in the select function as $layout->district_name
.
Upvotes: 0
Reputation: 315
$layout->districts()->first()->district_name
Will show the first district. If you have more than one, you can change first to get(). Then you'll need another foreach.
Upvotes: 0
Reputation: 643
Change your model so it knows about foreign key
Area:
public function districts(){
return $this->belongsTo('App\Districts','district_id','id');
}
public function municipals(){
return $this->belongsTo('App\Municipals','Municipal_uid','id');
}
Municipal:
public function district(){
return $this->belongsTo('App\Districts','district_id','id');
}
District:
public function municipal(){
return $this->hasMany('App\Municipals','id','district_id');
}
Upvotes: 2