0
votes

I'm trying to learn eloquent relationships. My relation is something like: Users hasMany posts and a post belongs to a user.

when I run my queries in tinker it shows errors.

$user->new User();
$user->all(); //Displays all the users
but i cannot do
$user->all()->posts;

it returns an empty array but If I do something like:

$posts = new Post();
$posts->all();
$post->users;

Error: Exception with message 'Property [post] does not exist on this collection instance.'

How can I achieve something like I want to have the users associated with posts or precisely I want users who have written posts.

2

2 Answers

0
votes

Base on the code you write the new User is missing a parenthencies. It should be like this

$user = new User();// Initialize the user model class
$user->all(); //get all users
$userpost =  $user->posts // link the user model to the post

Try these it will resolve the error.

0
votes

Use this:

$usersWithPosts = User::has('posts')->get();