[英]Trying to get property 'name' of non-object error in laravel eloquent
Self join in Eloquent in category
Model自加入 Eloquent
category
Model
public function parent()
{
return $this->belongsTo(Category::class, 'parent_id');
}
In blade file:在刀片文件中:
@foreach($categories as $category)
<tr>
<td>{{ $category->parent }}</td> // error in this line
</tr>
@endforeach
When I do this, it shows:当我这样做时,它显示:
{
"id": 1,
"name": "mobile",
"description": null,
"image": null,
"parent_id": 0,
"created_at": null,
"updated_at": null
}
When I change <td>{{ $category->parent }}</td>
to <td>{{ $category->parent->name }}</td>
, it shows error like:当我将
<td>{{ $category->parent }}</td>
更改为<td>{{ $category->parent->name }}</td>
时,它显示如下错误:
Trying to get property 'name' of non-object (View: C:\Users\HP\Desktop\laravel-project\laravel_ecommerce\resources\views\admin\pages\category\index.blade.php)
试图获取非对象的属性“名称”(查看:C:\Users\HP\Desktop\laravel-project\laravel_ecommerce\resources\views\admin\pages\category\index.blade.php)
How can I access $category->parent->name
?如何访问
$category->parent->name
?
If the parent has no child, then you will get this error.如果父母没有孩子,那么您将收到此错误。 The below example will throw
No Child
as output if the parent object is empty:如果父 object 为空,则以下示例将
No Child
作为 output 抛出:
{{ $category->parent->name ?? 'No Child' }}
Actually your getting this because of hasMany relationship relationship like this.其实你得到这个是因为有很多这样的关系。
{{$category->parent?$category->parent->name:"Some other message"}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.