FareedR
2 weeks ago

Helpers on contains

Posted 2 weeks ago by FareedR

currently im doing like post and unlike post , related model is Post , LikePost . why i still getting false on contains function. am i missing something ?

// database
id | post_id | user_id |
1   2       1

// User.php
public function posts()
    {
        return $this->hasMany(Post::class, 'user_id');
    }

// Post.php
public function likes()
    {
        return $this->hasMany(LikePost::class, 'post_id');
    }

// LikePost.php
public function posts()
    {
        return $this->belongsTo(Post::class,'post_id');
    }

    public function user()
    {
        return $this->belongsTo(User::class,'user_id');
    }

// Controller 
$posts = Post::where('available_qty','!=',0)->where('expired_at', '>=', now())->orderBy('expired_at', 'desc')->where('status', 'published')->get();

        $newPost = [];
        foreach($posts as $post) {
            $post['isLiked'] = 0;
            dd($post->likes->contains('user_id', $user_id)); // false
            if ($post->likes->contains('user_id', $user_id)) {
                $post['isLiked'] = 1;
            }
            $newPost[] = $post;
        }

        if (count($posts)) {
            return response()->json(['status' => true, 'result' => $newPost]);
        }

Please sign in or create an account to participate in this conversation.