Reputation: 543
I have two tables; Students and Grade. Students contains foreign key grade_id referencing Grade. For viewing students, I have used following code; Controller:
public function viewStudent()
{
$students=Student::all();
return $students('grade_id');
$grade = Grade::find($id, ['id', 'grade_name']);
return view('students.view',compact('students'));
}
View:
<tbody>
@foreach($students as $student)
<tr class="info">
<td>{{$student->first_name}}</td>
<td>{{$student->middle_name}}</td>
<td>{{$student->last_name}}</td>
<td>{{$student->grade_id}}</td>
</tr>
@endforeach
</tbody>
Model:
class student extends Model
{
//
protected $fillable = ['first_name','middle_name','last_name','grade_id'];
}
It shows grade_id as i have called it. But I want grade_name instead of that. Can anyone help me?
Upvotes: 0
Views: 7016
Reputation: 977
In Model
class student extends Model
{
protected $fillable = ['first_name', 'middle_name', 'last_name', 'grade_id'];
public function grade()
{
return $this->belongsTo('Grade');
}
}
In Controller
$students = Student::with('grade')->get();
In View
@foreach ($students as $student)
$studentGradeName = $student->grade->name;
@endforeach
Upvotes: 1
Reputation: 40899
First you need to define a relation to Grade
in your student model:
class student extends Model
{
public function grade() {
return $this->belongsTo(Grade::class);
}
}
Then you should be able to eagerly load grades for students with
$students = Student::with('grade')->get();
and access student's grade name with
$student->grade->name
Upvotes: 2