0

Its my Db structure I have a student table as

students 
+-------+--------+----------+
|id     |  name  | group_id | 
+-------+--------+----------+                
|1      |  ali   |     1    |
|2      |  ahmad |     2    |
+-------+--------+----------+

groups
+------+-------------+
|id    |  group_name |
+------+-------------+                
|1     |     A       |
|2     |     B       |
+------+-------------+

Now I have to show Name from student table and group_name from Groups

StudentController

{
        $students = Student::orderBy('id', 'desc')->get();
        return view('student.index')->with(compact('students'));
    }

My View

@foreach($students as $student)

<td>{{ $student->name }}</td>
<td {{ $student->group_name }} </td>

Please help me to retrieve record from both tables I try with different methods but failed

2 Answers 2

2

You need to add relation method to the Student class:

public function group()
{
    return $this->belongsTo(Group::class);
}

where Group is a model's class of a groups table.

Then in the controller:

{
    $students = Student::orderBy('id', 'desc')->with('group')->get();
    return view('student.index')->with(compact('students'));
}

and in the view:

@foreach($students as $student)

<td>{{ $student->name }}</td>
<td {{ $student->group->name }} </td>
Sign up to request clarification or add additional context in comments.

6 Comments

what do you mean by student class where i have to add relation ?@Fillip Koblariski
Here: Student::orderBy('id', 'desc')->get(); <- Student is a class that extends the eloquent model's
it says public undefined syntax error, unexpected 'public' (T_PUBLIC) @Fillip Koblariski
Show your Student class
'<?php namespace App; use Illuminate\Database\Eloquent\Model; class Student extends Model { protected $fillable = ['name', 'group_id']; } public function group() { return $this->belongsTo(Groups::class); }'
|
0

One student belongs to only one group. so, relationship between the student and group is one to one.

In Students.php Model

public function group(){
   return $this->hasOne(Group::class,'id','group_id');
}

and in view you can get group name as

@foreach($students as $student)
      <td>{{ $student->name }}</td>
      <td>{{ $student->group->name }}</td>
@endforeach

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.