How to use Union query with Laravel Eloquent?

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Hello Dev’s
Hope all are okay. Today in this article, i will like to share with you how you can use union and union all query with laravel eloquent in laravel 5.*, laravel 6, laravel 7 and also in laravel 8 application.


Laravel eloquent provide us query builder and also they give us join, relationship, subquery and also union. But sometimes we need get all records from different two tables. At that time we need to use union or union all query. So here i am going to give you very short and simple example.

Here i will create two tables such as “product_silver” and another one “product_gold” with some dummy data. After that we will write union query. So let’s see bellow.

$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);

Read Also : Laravel 8 Pagination by using Ajax Example

Thanks for read this, I hope it will you. You can also follow us on Facebook.

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →