简体   繁体   中英

Trying to get property 'name' of non-object error in laravel eloquent

Self join in Eloquent in 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:

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)

How can I access $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:

{{ $category->parent->name ??  'No Child' }}

Actually your getting this because of hasMany relationship relationship like this.

{{$category->parent?$category->parent->name:"Some other message"}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM