i am making website using laravel and want to add functionality where user can see those posts which are liked or commented by those accounts which are followed by logged in user and exclude posts of logged in user. Actually i want to suggest posts to user.
Post Model
public function user() {
return $this->belongsTo(User::class);
}
public function likes()
{
return $this->hasMany(Like::class);
}
public function comments(): HasMany
{
return $this->hasMany(Comment::class);
}
public function likedByUsers()
{
return $this->belongsToMany(User::class, 'likes', 'post_id', 'user_id');
}
User Model
public function likes()
{
return $this->hasMany(Like::class);
}
public function followers()
{
return $this->belongsToMany(User::class, 'follows', 'following_id', 'follower_id');
}
public function following()
{
return $this->belongsToMany(User::class, 'follows', 'follower_id', 'following_id');
}
public function followsUser($user_id)
{
return $this->followers()->where('follower_id', $user_id)->exists();
}
i have tried this one but not works..
$user = Auth::user();
$userId = Auth::id();
$followingUserIds = DB::table('follows')
->where('follower_id', $userId)
->pluck('following_id');
$posts = Post::whereNotIn('user_id', [$userId]) // Exclude logged-in user's posts
->whereIn('user_id', $followingUserIds)
->orWhere(function($query) use ($followingUserIds) {
$query->whereHas('likes', function ($query) use ($followingUserIds) {
$query->whereIn('user_id', $followingUserIds);
})
->orWhereHas('comments', function ($query) use ($followingUserIds) {
$query->whereIn('user_id', $followingUserIds);
});
})
->withCount('likes') // Include the count of likes
->latest() // Order by the latest posts
->get();
return view('posts.index', compact('posts'));