Laravel Eloquent union() Query
In this tutorial, we will learn Laravel Eloquent union() Query Example. I would like to share how to use the union query in the Laravel application Example. In this tutorial, you will learn How to use union queries in Laravel with Example. And if you want to see an example of Laravel Eloquent union() Query example, then you are in the right place.
Laravel default provides an eloquent query builder and they give us relationship, subquery, join, and also union. and here we need some time to get matches record from two different tables at that time. so we need to use union. Now, I will give you a simple example with a table and also show you an output of the results.
First, we will create one table of users with dummy data. we will write union query and result also I show a screenshot:
Also read: Laravel 8 Eloquent inRandomOrder() Method Example
Users table
using DB
use DB;
$first_query = DB::table('users')->where('id',5);
$users = DB::table('users')->where('id',4)->union($first_query)->get();
dd($users);
using Model
use App\Models\User;
$first_query = User::where('id',5);
$users = User::where('id',4)->union($first_query)->get();
dd($users);
Nice article in Laravel. But if you think that you are new to Laravel & faced problems understanding the eloquent, then first of all you should learn about raw different MySql queries. There is a very good expnanation with a practical table example with all kinds of the join query.
https://flamontech.com/learn-mysql-join-between-tables-practical-example/
https://flamontech.com/learn-mysql-right-full-join-between-tables/
https://flamontech.com/learn-mysql-union-cross-self-join-between-tables/