In this article, I am going to show that you how we can use union and union all query in laravel application. From this tutorial, I will give you an example of Laravel union query. From this example, you will learn how to use union in Laravel.
Laravel eloquent provides query builder and they give us join, relationship, subquery and also union. Sometimes we need to merge to table query and need to make one collection. In that situation, you can use laravel union query. So here I am to give you a very simple example with tables and also show you the output of the result.
$silver = DB::table("product_x") ->select("product_x.name" ,"product_x.price" ,"product_x.quantity"); $gold = DB::table("product_y") ->select("product_y.name" ,"product_y.price" ,"product_y.quantity") ->union($silver) ->get(); dd($gold);
Read also: Avoid json_encode() and Use @json() Blade Directive in Laravel
Hope it can help you.