ItSolutionStuff.com

How to use Union Query with Laravel Eloquent?

By Hardik Savani • April 16, 2024
Laravel

In this post, i would like to share with you how we can use union and union all query in laravel 5, laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 application.

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 we will create two tables "product_silver" and "product_gold" with dummy data like as bellow. Then after we will write union query and result also i shown as screenshot, so let's see bellow:

product_silver table:

product_gold table:

Query:

$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:

I hope it can help you....

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel Eloquent updateOrCreate Example

Read Now →

Delete All Records from Table in Laravel Eloquent

Read Now →

Multiple orWhere Condition in Laravel Eloquent

Read Now →

Laravel Eloquent exists() and doesntExist() Example

Read Now →

Laravel Eloquent Where Query Examples

Read Now →

Laravel Many to Many Eloquent Relationship Tutorial

Read Now →

Laravel WhereIn() and WhereNotIn() with Subquery Example

Read Now →

Laravel - How to use Subquery in Select Statement?

Read Now →

Laravel Select with Count Query with Group By Example

Read Now →

Laravel Select with Sum Query Example

Read Now →

How to Concat Two Columns in Laravel?

Read Now →

Example of unionAll in Query Builder Laravel

Read Now →

Laravel Join with Subquery in Query Builder Example

Read Now →

How to Add Pagination with Union in Laravel?

Read Now →