I have a weird problem with the syntax of laravel (version 7) {{ }}, where I use PHP syntax like that:
<?php echo $thread->lastReply->user->name; ?>
I get my user displayed but with the blade syntax :
{{$thread->lastReply->user->name}}
I got this error:
ErrorException
Trying to get property ‘user’ of non-object
where could the problem come from?
edited:
the method lastReplay in thread is like this:
public function getLastReplyAttribute()
{
$lastReplay = $this->replies->last();
dd($lastReplay);
return $lastReplay;
}
and with dump :
ModelsReply {#3012 ▼
#table: "ww_replies"
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:10 [▼
"id" => "42"
"thread_id" => "45"
"user_id" => "1"
"title" => null
"body" => "Quia minima velit illo aut vitae eum et. Fuga consequatur atque earum fuga ad aut molestiae. Expedita ratione perspiciatis laborum hic quis unde. Numquam ipsam ▶"
"slug" => null
"ip" => null
"created_at" => "2020-11-23 12:24:19"
"updated_at" => "2020-11-23 12:24:19"
"deleted_at" => null
]
#original: array:10 [▶]
#changes: []
#casts: []
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
}
4
Answers
Is your query returning array or object? If you dump it out, you might find that it’s an array and all you need is an array access ([]) instead of an object access (->).
it’s mean
$thread->lastReply
is not an object or usually it’snull
. to handle you can use condition example:or
you problem come from
->lastReply
. Maybe some users dont have alastReply
?Try the following:
This error mean either lastReply is returning null or its array
In this syntax you need to check some data before adding relationships
dump if lastReply is returning data
{{dd($thread->lastReply)}}
user should exists in model and have right foreign key in relationship.Also it should not be null that you can also check by following code
{{dd($thread->lastReply->user)}}
If both dumps returning data then it means lastReply or user is returning array. So you need to use array [] syntax to get data.
You can also use
{!! !!}
to print data to escape content