Andreas Hunter
Andreas Hunter

Reputation: 5004

Laravel: How to write two query in one query and get result from database?

I have sample code for get all trashed messages current user:

$query1 = $inbox->where('recipient', $user_id)
                ->where('trashed_in_recipient', 1)
                ->where('show_in_recipient', '!=', 1)
                ->orderBy('created_at', 'desc')
                ->paginate($paginate);

$query2 = $inbox->where('sender', $user_id)
                ->where('trashed_in_sender', 1)
                ->where('show_in_sender', '!=', 1)
                ->orderBy('created_at', 'desc')
                ->paginate($paginate);

How can be writed two query in one and get finally result?

Table structure:

enter image description here

Upvotes: 2

Views: 1050

Answers (1)

SyncroIT
SyncroIT

Reputation: 1568

You can use functions to define WHERE groups:

$query = $inbox->where(function($query) use ($user_id) {
    $query->where('recipient', $user_id);
    $query->where('trashed_in_recipient', 1);
    $query->where('show_in_recipient', '!=', 1);
})->orWhere(function($query) use ($user_id) {
    $query->where('sender', $user_id);
    $query->where('trashed_in_sender', 1);
    $query->where('show_in_sender', '!=', 1);
})->orderBy('created_at', 'desc')
  ->paginate($paginate);

I hope this helps you

Upvotes: 3

Related Questions