LARAVEL 5.6 - error Trying to get property 'nsc' of non-object

I want to echo value of NSC from table Group Class but i get this error Trying to get property 'nsc' of non-object

Table Item Name

Table Group Class

Model Item Name

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ItemName extends Model
{
    protected $table = 'tbl_item_name';
    protected $fillable = [
        'inc', 
        'item_name', 
        'short_name', 
        'definition_eng', 
        'definition_ind'
    ];

    public function GroupClass()
    {
        return $this->belongsTo('App\GroupClass', 'nsc', 'inc');
    }
}

Model Group Class

namespace App;

use Illuminate\Database\Eloquent\Model;

class GroupClass extends Model
{
    protected $table = 'tbl_group_class';
    protected $fillable = [
        'inc', 
        'nsc', 
        'description', 
        'main_group'
    ];

    public function ItemName()
    {
        return $this->belongsTo('App\ItemName', 'inc', 'nsc');
    }
}

Blade

<td>{{ $ItemName->GroupClass->nsc }}</td>

Please help to solve this problem, thank you so much

1 answer

  • answered 2018-04-17 04:20 AddWeb Solution Pvt Ltd

    You should try this::

    Blade

    <td> {{ isset($ItemName->GroupClass) ?  $ItemName->GroupClass->nsc  : '' }} </td>
    

    Model Item Name

    public function GroupClass()
    {
         return $this->belongsTo('App\GroupClass', 'inc', 'nsc');
    }
    

    Model Group Class

    public function ItemName()
    {
        return $this->belongsTo('App\ItemName', 'nsc', 'inc');
    }