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

vandan's avatar
Level 13

Trying to get property of non-object

Blade file

@foreach ($information as $informations)

{{$informations->followups->description}}

{{$informations->followups->followupdate}}

@endforeach

Controller file

    $information=Registration::where('id','=',$id)->get();

return view('view',compact('information'));   

 

Model followup

public function registrations()

{

    return $this->hasMany('App\Registration');

}

Registration Model

public function followups()

{

   return $this->belongsTo('App\Followup','student_id');

}

0 likes
18 replies
Snapey's avatar

or use null coalesce operator whenever you have two or more arrows in variable

{{ $informations->followups->description ??  'Not Set' }}

{{ $informations->followups->followups ??  'Not Set' }}

get in the habit of doing this whenever you see x->y->z

1 like
dragoneyes96's avatar

Your query should be

$information=Registration::with('followups')->findOrFail($id);

Remember to declare relationship in registration model. And in blade use null coalesce operator

munazzil's avatar

@vandan Are you sure your getting id not student_id in that Registration model?.

munazzil's avatar

Change as like below and check

                  $information=Registration::where('student_id','=',$id)->get();

else

                $information=Registration::where('student_id','=',$student_id)->get();
1 like
Snapey's avatar

If you query like this

$information=Registration::with('followups')->findOrFail($id);

Then you also need to remove the foreach loop in the view since this will find and return only one model

amd's avatar

Does this work. @snapey he already said that the data is null then how do you know that data is one collection?

Snapey's avatar
Snapey
Best Answer
Level 122

@amd

ok, break it down

$information=Registration::where('id','=',$id)->get();

This was the original code. It uses get(). This will return a collection of $information even if there is only one result.

So, the OP has found that a foreach is needed

@foreach ($information as $informations)

Then, later it is established that OP should eager load the relation

$information=Registration::with('followups')->findOrFail($id);

Now, this is possibly working, but will not work for OP in the view because they are @foreach on information

This is no longer necessary since findOrFail only returns a single model, so the view can be just

{{ $information->followups->description ?? 'Not Set' }}

{{ $information->followups->followupdate ?? 'Not Set' }}

happy to argue it out

I concede that the relationships could all be to whack, but we've got to start somewhere

Snapey's avatar

'Nothing work' .. what, do you even have electricity? have you switched the computer on? Are there any characters on the screen?

Please or to participate in this conversation.