Throughout Laravel Eloquent union query example tutorial you will learn how to use union query builder in laravel application. The query builder also provides a convenient method to “union” two or more queries together. The use of laravel union query used to get matches record.
Laravel eloquent provide query builder and they give us join, relationship, subquery and also union. But we need some time to get all records from two different table at that time you need to use union or union all query. So here i am going to give you very simple example with tables and also show you output of result.
Here in this screenshots you can check we have two records then how can you use union query one to another record.
Laravel Union Example
In this example we have get the first record then again get the second record then union the first record with secord.
use App\Models\User;
class UserController extends Controller
{
public function index()
{
$first = User::where('id', 1);
$users = User::where('id', 2)->union($first)->get();
dd($users->toArray());
}
}
Output:
Here will the output you can check below.
array:2 [▼
0 => array:8 [▼
"id" => 2
"name" => "Test 2"
"email" => "test002@gmail.com"
"email_verified_at" => null
"created_at" => "2021-10-31T09:53:35.000000Z"
"updated_at" => "2021-10-31T09:53:38.000000Z"
"first_name" => "Test"
"last_name" => "Two"
]
1 => array:8 [▼
"id" => 1
"name" => "Test 1"
"email" => "test001@gmail.com"
"email_verified_at" => null
"created_at" => "2021-07-17T19:13:54.000000Z"
"updated_at" => "2021-07-17T19:13:54.000000Z"
"first_name" => "Test"
"last_name" => "Demo"
]
]
In addition to the union
method, the query builder provides a unionAll
method. Queries that are combined using the unionAll
method will not have their duplicate results removed. The unionAll
method has the same method signature as the union
method.
I hope this will help you…