Moawia Meghari Moawia Meghari - 1 year ago 63
Javascript Question

return all users each user with posts and each post with comments laravel

I am using laravel eloquent and I made models (User,Post,Comment)

the relaitions is

User model

public function posts(){
return $this->hasMany('App\Post');

public function comments(){
return $this->hasMany('App\Comment');

Post model

public function comments()
return $this->hasMany('App\Comment');
public function user()
return $this->belongsTo('App\User');

Comment model

public function post()
return $this->belongsTo('App\Post');

I Want to return all users and each user has an object of his posts and each post of those has an object of all comments

I have this query

$users = \App\User::with('posts')->\get();
return $users;

it returns objects of users and each user have object of his posts, but no comments object

now the problem is

in php, e.g. I can
return user[0]->posts[0]->coments()

and it return the comments

but I can not see this comments in javascript or mobile phones as API
it returns "try to get property of non object"

so .. I want to use the comments in js or API

I can get the comments using for loop but I looking for better solution

Answer Source

You can do it like this:

$users = \App\User::with('posts', 'posts.comments')->get();
return $users;

Hope this helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download