Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Flex's avatar
Level 4

how to print province name using province_id in laravel 5.6

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 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 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
0 likes
20 replies
Flex's avatar
Level 4

No any idea about this matter?

topvillas's avatar

Maybe wait for more than fifteen minutes before moaning that nobody's solved your problem for you.

1 like
Cronix's avatar
Town::with('district.province')

This is pretty simple. You have to go through the data just like the nested relationship.

$town->district->province->name

If you dd($town_list);, this should be pretty obvious if you actually look at the data you're working with. Always a good thing to do when in doubt.

jlrdw's avatar

Could you possibly show how you want the data to be displayed and is this a report.

Flex's avatar
Level 4

@Cronix occured this error msg

Trying to get property of non-object (View: C:\Users\Flex\Desktop\btx\resources\views\cars\carform.blade.php)
Cronix's avatar

dd() your data and LOOK at it. Show us.

cmdobueno's avatar

... inside your foreach for towns

@php dd($town); @endphp
36864's avatar

Or just dd($town_list) in your controller so you can check them all at once

Flex's avatar
Level 4
 @foreach($town_list as $town)
            dd($town);
            <option value="{{$town->provinceid}}">{{$town->provinceid}}</option>
            @endforeach

this is show my blade view normaly without any error

Flex's avatar
Level 4

but inside controller,

public function show($id)
    {
        dd($town_list);
   
        $town_list = Town::with('district.province')->groupBy('provinceid')->get();
    return view('cars.carform')->withTown_list($town_list);
    }

its occurred this error msg

Undefined variable: town_list
Cronix's avatar

In controller

$town_list = Town::with('district.province')->groupBy('provinceid')->get();
dd($town_list->first());

I believe the problem is your groupBy, which will change how the results are returned.

36864's avatar

Obviously you need to set the variable before you can dump it out...

Flex's avatar
Level 4

@Cronix occured this message,

Town {#283 ▼
  #connection: "mysql"
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:6 [▼
    "id" => 1
    "townname" => "Eheliyagoda"
    "districtid" => 1
    "provinceid" => 1
    "created_at" => null
    "updated_at" => null
  ]
  #original: array:6 [▼
    "id" => 1
    "townname" => "Eheliyagoda"
    "districtid" => 1
    "provinceid" => 1
    "created_at" => null
    "updated_at" => null
  ]
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #events: []
  #observables: []
  #relations: array:1 [▼
    "district" => null
  ]
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
  #guarded: array:1 [▼
    0 => "*"
  ]
}

Cronix's avatar

So your relationships aren't working, or you don't have a district for that town. Notice district is null

Cronix's avatar

Try this

$town_list = Town::with(['district', 'province'])->get();
dd($town_list->first());

And in the Town model, add

public function province()
{
    return $this->belongsTo(Province::class);
}
Flex's avatar
Level 4

@Cronix it got

Town {#287 ▼
  #connection: "mysql"
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:6 [▼
    "id" => 1
    "townname" => "Eheliyagoda"
    "districtid" => 1
    "provinceid" => 1
    "created_at" => null
    "updated_at" => null
  ]
  #original: array:6 [▼
    "id" => 1
    "townname" => "Eheliyagoda"
    "districtid" => 1
    "provinceid" => 1
    "created_at" => null
    "updated_at" => null
  ]
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #events: []
  #observables: []
  #relations: array:2 [▼
    "district" => null
    "province" => null
  ]
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
  #guarded: array:1 [▼
    0 => "*"
  ]
}

Cronix's avatar

Man this is messy lol. In your first post you showed us your db tables and field names seems to be wrong. Actually, it's right (if it was actually that), but according to your data, it's wrong.

You said you had these 2 fields in the towns table

district_id
province_id

according to the data you just showed, that's not correct.

"districtid" => 1
"provinceid" => 1

No _ between the table name and id.

If they actually were district_id and province_id (like how they should be), this would probably work.

It would be best to change them to be proper, or you'll have to manually add the fk's to your relationship definitions.

Please read this: https://laravel.com/docs/5.6/eloquent#eloquent-model-conventions

Flex's avatar
Level 4

@Cronix in my towns table I have districtid and provinceid columns ,

district_id
province_id

is wrong when I post this post sorry....

Please or to participate in this conversation.