Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Mephisto's avatar

Laravel Trying to access array offset on value of type null

After deleting one adviser. this error shows "Trying to access array offset on value of type null". can you help me fix this. thank you.

Adviser model:

public function students()
    {
        return $this->hasMany(Student::class);
    }

public function getAdviserNameAttribute()
    {
        return $this->first_name.' '.$this->last_name;
    }

Student model:

public function advisers()
    {
        return $this->belongsTo(Adviser::class, 'adviser_id');
    }

student migration:

$table->BigInteger('adviser_id')->unsigned()->nullable();
$table->foreign('adviser_id')->references('id')->on('advisers')->onDelete('set null');

index.blade.view:

<td>
	{{ $student->advisers['advisername'] }}							
</td>	

controller:

  public function index()
    {
        $students = Student::paginate(5);
        $users = User::all();
        $advisers = Adviser::all();
       
        return view ('admin.index', compact('students', 'users', 'advisers'));
    }

//delete adviser
     public function deleteAdviser(Adviser $adviser)
    {
        $adviser->delete();

        return redirect()->back()->with("error","Deleted!");
    }
0 likes
3 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

If it does not have an advisor you need a fallback

{{ $student->advisers['advisername'] ?? '' }}
1 like
MichalOravec's avatar

@mephisto In student model change relationship name to singlular form, because it is belongsTo relationship

public function adviser()
{
    return $this->belongsTo(Adviser::class);
}

In Adviser model don't use same prefix as model name in accessor, instead use for example full name

public function getFullNameAttribute()
{
    return "{$this->first_name} {$this->last_name}";
}

Then in blade it should be

{{ optional($student->adviser)->full_name }}

// or

{{ $student->adviser->full_name ?? '' }}
1 like

Please or to participate in this conversation.