Laravel Eloquent union() Query Example

10-Apr-2023

.

Admin

Laravel Eloquent union() Query Example

In this post, I would like to share with you how to use union query in laravel application.

The use of laravel union query used to get matches record.

Laravel eloquent provides query builder and they give us join, relationship, subquery, and also union but we need sometime to get matches record from two different table at that time you need to use union. So here i will give you very easy and simple example with table and also show you with output of results.

Here I will create one table "users" with dummy data like as bellow after that we will write union query and result also i show as screenshot. So let's see bellow examle.

Users Table


Query 1

$first = DB::table('users')

->where('id',8);

$users = DB::table('users')

->where('id',2)

->union($first)

->get();

Query 2 with Model

$first = User::where('id',8);

$users = User::where('id',2)->union($first)->get();

Output :

It will help you...

#Laravel 7

#Laravel

#Laravel 6