Home Laravel How to use Union query with Laravel Eloquent?

How to use Union query with Laravel Eloquent?

by Shahriar Sagor

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.Here we will know about Union query with Laravel Eloquent.


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.

close

You may also like