0

I have two Model, School, and Student the relationship is, School has Many Student //Student Model

public function school()
    {
        return $this->belongsTo('App\School');
    }

and same in School Model the following is the function for relationship

public function student()
    {
        return $this->hasMany('App\Student');
    }

Now I have a show Page I like to display the following information. (school_name,school_code) from the school table and student information all from the Student Table.using show function in student controller if I pass as

 public function show($id)
        {
            $student=Student::find($id);
            $school=School::find($id);   
     return View::make('student.show')->with(['school'=> $school,'student'=>$student]); 
}

it gets data from school if school_id ==$id but one school has many students it fails if I click to show a button with an ID of 109, how to write the Join query to get school_code and school_name from schools table.

inasar
  • 51
  • 1
  • 8
  • 1
    you have a show page ... to show what? the shool or the student? – lagbox Jun 30 '20 at 14:50
  • Try eager loading `Student::with('school')->find($id);` – STA Jun 30 '20 at 14:52
  • 2
    may I also recommend to rename the realationship to `students` instead of `student` since it is a "many" relationship and will return a collection **always** (plural) – lagbox Jun 30 '20 at 14:55

3 Answers3

2

Not sure why you are using the same $id to getting student and school

public function show($id)
{
    $student = Student::find($id);
    $school = $student->school; //school of the student
    return View::make('student.show')->with(['school'=> $school,'student'=>$student]); 
}

Use this code

Mubbashar
  • 613
  • 6
  • 15
0

Your model should be like this

public function students()
{
    return $this->hasMany('App\Student');
}

You have to change like this.

$student = Student::find($id);
$school  = $student->school;
A.A Noman
  • 5,244
  • 9
  • 24
  • 46
0

Since you have the relationship setup already, you could use Eloquent to fetch data for single student with the school that he belongs tos as follow:

public function show($id)
{
  $student = Student::with('school')->where('id', $id)->first();
  return View::make('student.show')->compact('student); 

}

Now you can retrieve data show.blade.php as follow:

@foreach($student as $stud)
  <li> {{ $stud->student_name}}</li>
  <li> {{ $stud->student_code}}</li>
  <li> {{ $stud->->school->school->name}}</li>
  <li> {{ $stud->school->school_name }}</li>
@ndforeach
livreson ltc
  • 733
  • 8
  • 22