Skip to content
Advertisement

How to get foreign key from eloquent collection in laravel

I have hasMany relationship in my User model;

JavaScript

I need to get a foreign id in Eloquent data

Controller;

JavaScript

Expected output;

1

How can I get the foreign key?

Advertisement

Answer

You can do the following. Since posts has hasmany relation so it return collection of object even though you have one item in posts.

JavaScript

or

JavaScript

If you still need one item from posts relationship then you can add one relationship

JavaScript

then you can access

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement