Reputation: 45
I have 3 tables: posts
, votes
and users
. I want to exclude that posts that were already voted by the current user (Auth::user()->id). How should I achieve that? I tried with this code:
$user_id = Auth::user()->id;
$posti = Post::with('user')
->whereDoesntHave("votes")
->whereBetween('posts.created_at', array(Carbon::now()->subHours(48), Carbon::now()))
->orderBy('posts.created_at', 'DESC')
->orderByVotes()
->take(20)
->get();
Upvotes: 2
Views: 210
Reputation: 424
You can check if posts don't have votes from the logged in user using votes relation and callback function. To achieve this use the code below:
$userId = Auth::user()->id;
Post::with('votes')
->whereDoesntHave('votes', function ($query) use ($userId) {
$query->where('user_id', $userId);
})
->get();
Upvotes: 2
Reputation: 135
You can also use the relationship in if condition to check if logged user already voted or not like:
$user = Auth::user()->id;
@if($user->votes)
@else
Upvotes: 0