简体   繁体   中英

eloquent returning null value in laravel 5.6

I am doing a simple logic. I have 2 tables, attribute_type, and attribute_sub_type. In AttributeSubType model, I have created this function.

 public function attribute_types()
{
    return $this->belongsTo('App\Models\AttributeType');
}

And in AttributeType model, I have created this function.

public function attribute_sub_type()
{
    return $this->hasMany('App\Models\AttributeSubType');
}

My View is:

@foreach($attributeSubTypes as $attributeSubType)
    <tr>
        <td>{!! $attributeSubType->attribute_types['attribute_type'] !!</td> //this line returning null by dd($attributeSubType->attribute_types['attribute_type'])
    </tr>
@endforeach

Where 'attribute_type' is a column in attribute_type table. I have used the same logic in another project. And that is working like charm.

I have solved the problem by creating this method in the AttributeSubType model.

public function getAttributeType($id)
{
    $attribute = AttributeType::find($id);

    return $attribute->attribute_type;
}

And this is how I call it in View.

@foreach($attributeSubTypes as $attributeSubType)
    <tr>
        <td>{!! $attributeSubType->getAttributeType($attributeSubType->attribute_type_id) !!}</td>
</tr>
@endforeach

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