PHP Laravel 7.x and 6.x Union query Example

September 18, 2018 | Category : Laravel PHP

Hi Guys,

Are you looking for how to use union in laravel query builder? If yes then you are a right place.

Here i will show you example of union query in laravel 5 project. You can simply user union mysql query by using union() of laravel eloquent.

Here i write union query for two tables and get both tables data like as bellow query result:

Example:

$silver = DB::table("product_silver")

->select("product_silver.name"

,"product_silver.price"

,"product_silver.quantity");

$gold = DB::table("product_gold")

->select("product_gold.name"

,"product_gold.price"

,"product_gold.quantity")

->union($silver)

->get();

dd($gold);

Output:

Collection {#233 ▼

#items: array:5 [▼

0 => {#235 ▼

+"name": "Speaker"

+"price": 500

+"quantity": 100

}

1 => {#237 ▼

+"name": "Mobile"

+"price": 200

+"quantity": 100

}

2 => {#238 ▼

+"name": "Mobile"

+"price": 100

+"quantity": 500

}

3 => {#239 ▼

+"name": "Laptop"

+"price": 200

+"quantity": 600

}

4 => {#240 ▼

+"name": "Tables"

+"price": 600

+"quantity": 100

}

]

}

I hope you found your best solution...