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

vipin93's avatar
Level 13

How to show city name same page?

I have students table where in I made two collome city_id and ccity_id but one for permanent address and one for communication address But its related to same city so like one city_id=2, ccity_id=3 so here how can I show in view

My model City.php

class City extends Model
{
      protected $fillable = [
        'name'
    ];

    public function students()
    {
        return $this->hasMany(Student::class);
    }

Student.php

class Student extends Model
{
      protected $fillable = [
        'student_name', 'address','city_id','state_id','zip_pin', 'address1','ccity_id', 'cstate_id','avatar','zip_pin1'
    ];
public function city()
    {
        return $this->belongsTo(City::Class);
    } 

HomeController.php

public function index()
    {
      
        $students = Student::with('city')->get();
        
        return view('home',compact('students'));
    }

home.blade.php

permanent address
           @foreach($students as $s)
          address <p>{{$s->city->name}}  // here is city_id = 2

         @endforeach

communication address
           @foreach($students as $s)
          address <p>{{$s->city->name}}  // here is ccity_id = 5  so here how can i show 

         @endforeach


databse tabel is

students
id|student_name|address|city_id|address1|ccity_id

city
id|name

0 likes
4 replies
ohffs's avatar
ohffs
Best Answer
Level 50

You'd have to add another relation onto your model. Something like :

public function ccity()
{
  return $this->belongsTo(City::Class, 'ccity_id');
} 

Then you can use $s->ccity->name in the view.

vipin93's avatar
Level 13

@ohffs thanks its working one more question here below

 public function index()

    {
      
        $students = Student::with('city','states')->get();
        return view('home',compact('students'));
    }


State.php
public function students()
    {
        return $this->hasMany(Student::class);
    }


Student.php

 public function states()
    {
        return $this->belongsTo(State::Class);
    } 


home.blade.php

@foreach($students as $s)
           <p>{{ $s->city->name }}</p>
           <p>{{ $s->states->name }}</p>  //state_id =2

@endforeach

its showing error Trying to get property of non-object

ohffs's avatar

I guess either the city or states is empty. Try wrapping it in an @if clause so you can see?

<p>
@if ($s->city)
  {{ $s->city->name }}
@else
  Student {{ $s->student_name }} has no city
@endif
</p>

and do the same for the $s->states. Then you can check the student record and see if it's really empty or something is going wrong in the relation :-)

vipin93's avatar
Level 13

I add state_id in Student. php and its working thanks for replyin

Please or to participate in this conversation.