Search code examples
phplaraveleloquentlaravel-artisantinker

Cannot specify 'title' from product table - php artisan tinker


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.


Solution

  • 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