Reputation: 402
I am developing app using laravel 5.6
.
In my application I have three tables as provinces, districts, towns and these models have following relationship:
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 eager loder in Controller
:
$town_list = Town::with('district.province')->groupBy('provinceid')->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->provinceid}}">{{$town->provinceid}}</option>
@endforeach
</select>
</div>
now I can see provinceid 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
Upvotes: 0
Views: 205
Reputation: 1639
Firstly, you can remove that province_id
from your Town
table. District of the town gives you required province id ($town->district->province_id
or $town->district->province->id
).
Also, to print Province name, you can chain your relationships. As mentioned, you can get it using $town->district->province->name
.
<option value="{{$town->district->province->id}}">{{$town->district->province->name}}</option>
Upvotes: 1