'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



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1