One to one relationship : ORM

Viewed 35

I am new to laravel framework and working on one-to-one relationship. I have created a table of student and phone. I am trying to get a student who has a phone number. but i get an error.

enter image description here

enter image description here

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    use HasFactory;

    // protected $table = 'stdnt';

    //protected $primaryKey = 'student_id';
    //public $timestamps = false;

    // One to one relationship
    public function rPhone()
    {
        return $this->hasOne(Phone::class);
    }
}

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Phone extends Model
{
    use HasFactory;
}


@foreach ($all_students as $item)
    Name: {{ $item->student_name }} <br>
    Email: {{ $item->student_email }} <br>
    Phone: {{ $item->rPhone->phone }} <br><br>
@endforeach

enter image description here

enter image description here

enter image description here

1 Answers

The error is informing you that the value of $item->rPhone is null. You can't access properties on a null object. This tells you the relationship is failing.

Looking at the screenshots of your database records, you have a Student record with an ID of 5 but no related record in your phones table with a student_id of 5 to match. Therefore the relationship doesn't exist and hence a null reference.

A simple solution for this is to either create a new record in your phones table with a student_id of 5 or update an existing record and set the student_id to 5.

Alternatively, you could limit the records you return based on relationship existance or perform some null reference checking in your view when accessing the relationship.

What you could do in your Blade view, is make use of the optional helper to prevent the error from being thrown. This would also allow you to identify which record(s) are causing the issue.

Phone: {{ optional($item->rPhone)->phone }}

After using your modified codes Phone: {{ optional($item->rPhone)->phone }} is now working. But i still dont understand. Kindly explain to me better.

As I have already mentioned and as per the error you're getting, one or more of your Student records does not have a related Phone record. Which Student records are causing the error I can't tell you but using the aforementioned optional helper should tell you which as you'll see some of your @foreach output missing a Phone value.

All the optional helper is doing is performing a null check on the value you provide it and handling the 'error' gracefully rather than causing an exception to be thrown.

Related