Reputation: 402
I am developing app using laravel 5.6. in my application I have three tables as provinces,districts,towns and My models have following relationship with each models,
Province
public function districts()
{
return $this->hasMany(District::class);
}
District
public function province()
{
return $this->belongsTo(Province::class);
}
Town
public function district()
{
return $this->belongsTo(District::class);
}
now I have data grab using towns table in Controller,
$town_list = DB::table('towns')
->groupBy('province_id')
->get();
and dropdown selection input in blade file,
<div class="form-group">
<label for="exampleFormControlSelect1">Province</label>
<select name="province_id" id="province_id" class="form-control input dynamic" data-dependent="district_id" >
<option value="">Select Province</option>
@foreach($town_list as $town)
<option value="{{$town->province_id}}">{{$town->province_id}}</option>
@endforeach
</select>
</div>
now I can see province_id in My selection input but I need print province name in my selection input, my table structure,
provinces
id name
1 alabama
2 prodova
districts
id name province_id
1 x 1
2 y 2
towns
id name district_id province_id
1 gh 1 1
2 ju 2 2
how can do this?
Upvotes: 0
Views: 659
Reputation: 568
Try use eager loading:
$towns = Towns::with('district.province')->groupBy('province_id')->get();
Now you can loop in your view and call the province name.
Upvotes: 1