-2

i'm developping a social app using React in the frontend and laravel in the backend. I'm trying to receive all posts with their likes,users,comments. I have these relation ships: 1/ User model has many posts and Post model belongs to a user. 2/ Post model has many likes 3/ Post model has many comments and one comment belongs to a user. When getting all posts back, im succefully getting its likes and users information, but for comments i wanna get the user's comment. So i did $posts->comments->user->user_name And then, i got the error: Property [user] does not exist on this collection instance. But when i tried to get comments infos, it worked normally($posts->comments) My comment relation in Post model:

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

My user relation in Comment Model:

public function user()
    {
        return $this->belongsTo('App\Models\User');
    }

My method in PostController when i'm trying to get all posts:

public function allPosts()
    {
        $posts = Post::with('user','likes','comments')->get(); 
        if($posts->count() < 1) {
            return response()->json([
                'success' => false,
                'message' => 'There are no posts!'
            ]);
        }else {
            return response()->json([
                'success' => true,
                'data' => PostResource::collection($posts),
                'message' => 'Succefully retreived all posts!'
            ]);
        }
    }

As you noticed i'm sending the Data through a Resource, so My PostResource's method :

public function toArray($request)
    {
        // return parent::toArray($request);
        return [
            'id' => $this->id,
            'user_id' => $this->user_id,
            'content' => $this->content,
            'image_path' => $this->image_path,
            'user' => $this->user,
            'likes' => $this->likes->count(),
            'isLiked' => $this->likes->where('user_id', auth()->user()->id)->isEmpty() ? false : true,
            'comment_user' => $this->comments->user->user_name,
            'created_at' => $this->created_at->format('d/m/y'),
            'updated_at' => $this->updated_at->format('d/m/y')
        ];
    }

As i said, everything is okey, just for comment_user it says:Property [user] does not exist on this collection instance, and when i tried to get only comments info it worked:

'comments' => $this->comments,

Any help please? and thnx in advance.

1 Answers1

0

Maybe you need to add relation user() to Post model?