Ramzan Mahmood
Ramzan Mahmood

Reputation: 1901

Laravel retrieve data from multiple tables

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

Upvotes: 0

Views: 67

Answers (2)

Balraj Allam
Balraj Allam

Reputation: 611

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

Upvotes: 0

Filip Koblański
Filip Koblański

Reputation: 9988

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>

Upvotes: 2

Related Questions