0

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

1. Products table :

  • ID (int)
  • Title (String)
  • fabric (unsignedInteger)
  • created_at (timestamp)
  • I have also used this code below in migration.
$table->foreign('fabric')->references('id')->on('fabrics');

2. Fabric Table

  • ID (int)

  • Title (string)

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

James Z
  • 12,209
  • 10
  • 24
  • 44
Ishaan
  • 1,249
  • 15
  • 26

3 Answers3

1

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!

Ishaan
  • 1,249
  • 15
  • 26
0

first of all, I assume that you have defined $fillable array within your fabric Model with title you should replace

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

by

@isset($product->fabric)

       {{ $product->fabric->title }}
@endisset
Thamer
  • 1,896
  • 2
  • 11
  • 20
  • it shows `Trying to get property 'title' of non-object`. – Ishaan Jul 28 '19 at 15:24
  • because you don't have any fabric related to that product in your database, you should add if test to check if you really have fabric related to that product – Thamer Jul 28 '19 at 15:32
0

You should either replace {{ $product->fabric()->title }} with {{ $product->fabric->title }}

or

You can replace it with $product->fabric()->get()->title;

What you are doing with your original line of code is trying to print out the relationship as opposed to the object returned.

Jason
  • 284
  • 2
  • 10
  • It shows `Trying to get property 'title' of non-object`. – Ishaan Jul 28 '19 at 15:26
  • Hmm try using ```var_dump($product->fabric)``` to see if what you get returned is an array. In that case, it isn't an object and should be accessed with something like ```$product->fabric["title"]``` – Jason Jul 28 '19 at 15:29
  • Thanks for your time but I got my error, actually I am using the **same name** for a function as well as for a property i.e. **fabric**. – Ishaan Jul 28 '19 at 15:31