Tijan Manandhar
Tijan Manandhar

Reputation: 332

How to do condition based query in Eloquent ORM, Laravel?

I want to get public timeline where I can access all public posts and get friends all posts (i.e may it be public or private). How can I manage it in one condition where I can get all public posts of everyone and private posts of friends. The code below is working for only public videos.

$friends = json_decode($this->friend->where('user', $this->currentUser->id)->first()->list, true);
$blockedUserArray = $this->getBlockedList();
$friends[] = $this->currentUser->id;
$videos = $this->video
        ->withCount('videoComment', 'videoLike')
        ->where('privacy', 'EVERYONE')
        ->orWhereIn('user', $friends)
        ->whereNotIn('user', $blockedUserArray)
        ->latest()
        ->paginate($this->videoPaginate);

I can do it with two queries, but it will effect in pagination. Is there any way to do it in a single query?

Upvotes: 0

Views: 86

Answers (1)

g4li
g4li

Reputation: 500

You must group these two query

->where('privacy', 'EVERYONE')
->orWhereIn('user', $friends)

to

->where($query, function($query) use ($friends) {
    $query->where('privacy', 'EVERYONE')
          ->orWhereIn('user', $friends);
})

Check the document Parameter Grouping

Upvotes: 1

Related Questions