laravel-5eloquentforeign-keys

How can i create a relation beetwen two models and pass the model info on to the view through the controller?


My Student Model

 /**
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function fathers()
{
    return $this->belongsTo('App\Models\Father');
}

My StudentController

/**
 * Display the specified resource.
 *
 * @param ManageStudentRequest $request
 * @param  int $id
 * @return \Illuminate\Http\Response
 */
public function show(ManageStudentRequest $request, $id)
{
    $student = Student::with('fathers')->find($id);

    return view('students.show')->withStudent($student);
}

And my Blade View

<tr>
    <th>NOMBRE</th>
    <td>{{ $student->father->first_name }} {{ $student->father->last_name }}</td>
</tr>

I get the following error:

Trying to get property of non-object (View: C:\laragon\www\App\resources\views\students\partials\show\show-overview.blade.php) (View: C:\laragon\www\App\resources\views\students\partials\show\show-overview.blade.php)

Solution

  • You should setup your structure to have a many to many relationship between students and fathers if that's the logic you want, so:

    public function fathers()
    {
        return $this->belongsToMany('App\Models\Father');
    
        //Also define the inverse relationship on the Father model.
    }
    

    Now assuming you've done that then:

    On this query $student = Student::with('fathers')->find($id); just append first() so it looks like this:

    $student = Student::with('fathers')->find($id)->first();

    Then in your view you can access them like this:

    <td>{{ $student->father->first_name }} {{ $student->father->last_name }}</td>