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.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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
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.
Please or to participate in this conversation.