Reputation: 331
I have a Laravel 5.8 application where one user can block another user.
User model:
public function blockedUsers()
{
return $this->belongsToMany(User::class, 'blocked_user', 'user_id', 'blocked_id');
}
Now every user can post articles. How to get all articles that are posted by non blocked users in users feed.
If I do:
$posts = Post::all();
Obviously I will get all posts, so how to make a where conditin and say all posts that are created by a user which is not blocked by Auth::user()
?
$user = Auth::user();
$posts = Post::where(function($q) use ($user){
// Can't figure out this part
})->get();
Upvotes: 0
Views: 621
Reputation: 1188
You can first get your blocked user ids and use it later in the query to check if the creator of the post is one of the blocked ids using whereNotIn()
$user = Auth::user();
// Get list of blocked user ids
$blockedIds = $user->blockedUsers->pluck('id')->toArray();
// NOTE: I am assuming the field that hold the post creator id is user_id
// Get all post where the creator id is not in the blocked ids array
$posts = Post::whereNotIn('user_id',$blockedIds)->get();
Alternatively you can also write it like this
$user = Auth::user();
$posts = Post::where(function($q) use ($user){
$q->whereNotIn('user_id', $user->blockedUsers->pluck('id'))
})->get();
Upvotes: 3
Reputation: 3679
$user_id = Auth::id();
// get all blocked users by auth user
// note: you need to create BlockedUser model for blocked_user table
$blocked_users=BlockedUser::where('user_id',$user_id)->pluck('blocked_id');
// get all posts without posts that created by blocked users
Post::whereNotIn('user_id',$blocked_users)->get();
Upvotes: 0