Reputation: 1523
can you please check why this code is returning me empty result in laravel. i am trying to fetch nations name based upon nation id in teachers table.
public function edit(Teacher $teacher)
{
$teachers= DB::table('teachers','nations')
->join('nations', 'teachers.nation_id', '=', 'nations.id')
->select('teachers.*')
->where('teachers.id',$teacher->id)
->first();
return view('teachers.create',['teachers' => $teachers]);
}
Upvotes: 0
Views: 1119
Reputation: 1814
Check this code
public function edit(Teacher $teacher)
{
$teachers= DB::table('teachers')
->join('nations', 'teachers.nation_id', '=', 'nations.id')
->select('teachers.*','nations.name')
->where('teachers.id','=',$teacher->id)
->first();
return view('teachers.create',['teachers' => $teachers]);
}
Upvotes: 1
Reputation: 1850
In case you allowed in teachers table for nation_id to be empty value or null, you need to use left join to still have all records from teachers table:
public function edit(Teacher $teacher)
{
$teachers= DB::table('teachers','nations')
->leftJoin('nations', 'teachers.nation_id', '=', 'nations.id')
->select('teachers.*', 'nations.name')
->where('teachers.id',$teacher->id)
->first();
return view('teachers.create',['teachers' => $teachers]);
}
Upvotes: 1
Reputation: 14288
Why do you need to use the query builder to perform such a not complex query?
You can achieve this easier if you add a relationship method in your Teacher
model.
So in your Teacher
class add the following:
public function nation() {
return $this->belongsTo(Nation::class);
}
Then in your controller you can use it like this:
$teacher->nation;
Upvotes: 1