2

Using php artisan tinker I'm able to pull a product table that relates to, in this example, the first user in my database

>>> App\User::first()->product;
=> Illuminate\Database\Eloquent\Collection {#2912
     all: [
       App\product {#2898
         id: 2,
         owner_id: 2,
         title: "ListingTestTitle",
         description: "ListingTestDescription",
         price: "420.69",
         created_at: "2019-11-08 13:21:28",
         updated_at: "2019-11-08 13:21:28",
       },
     ],
   }

However when I attempt to go into this collection further and just grab the title I get the following error

>>> App\User::first()->product->title;
Exception with message 'Property [title] does not exist on this collection instance.'

I get the same issue no matter which attribute I attempt to pull.

Overflow
  • 57
  • 7
  • 1
    As a sidenote, this is why correct variable naming is important. `product` is a singular noun, and should reflect a single instance, so having it return `hasMany()` in the form of a `Collection` is wrong. This relationship should be `products` if you want to use `hasMany()` and get multiple `Product` instances, or `product` if you want to use `hasOne()` or `belongsTo()` and get a single `Product` instance. Also, class names are `StudlyCase`, so `App\Product` instead of `App\product`. – Tim Lewis Nov 08 '19 at 15:29
  • I'll work on better naming conventions. Thanks a lot for the info – Overflow Nov 10 '19 at 16:14

3 Answers3

2

You can use hasOne relationship in your User Model

App\User::first()->product->first()->title;
VIKAS KATARIYA
  • 5,867
  • 3
  • 17
  • 34
1

Because product is a hasMany relationship in your User model, access the first one as well from the relationship collection

App\User::first()->product->first()->title;

Or just change the relationship to a hasOne

Hope this helps

Salim Djerbouh
  • 10,719
  • 6
  • 29
  • 61
0
App\User::first()->product->first()->title;
Imanali Mamadiev
  • 2,604
  • 2
  • 15
  • 23