laravel-5.7table-relationships

Error in relationships between two tables in laravel


I am developing an e-commerce project in which I have the following tables,

1. Products table :

$table->foreign('fabric')->references('id')->on('fabrics');

2. Fabric Table

My models are:

    class Product extends Model{
        public function fabric(){
            return $this->hasOne('App\Fabric','id', 'fabric');
        }
    }

    class Fabric extends Model{
            public function products(){
                return $this->belongsTo('App\Product', 'fabric', 'id');
            }
        }

I want to get the product fabric in view using this

      {{ $product->fabric()->title }}

However, it returns

Object of class Illuminate\Database\Eloquent\Relations\HasOne could not be converted to string


Solution

  • One cannot use the same name for the property as well as for function as what I am doing there, I am using fabric for both the function as well as for the property.

    So I changed my table column from fabric to fabric_id.

    It works!