Skip to content

All topics  /  Laravel

Laravel Eloquent union() Query Example

Laravel ·

Teams applying “Laravel Eloquent union() Query Example” in a production project can use competency gap analysis to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.

Before copying the example into a live application, confirm version-specific behaviour with the official Laravel website and test it against the project’s actual database and runtime.

In this post, I would like to share with you how to use union query in laravel application.

The use of laravel union query used to get matches record.

Laravel eloquent provides query builder and they give us join, relationship, subquery, and also union but we need sometime to get matches record from two different table at that time you need to use union. So here i will give you very easy and simple example with table and also show you with output of results.

Here I will create one table "users" with dummy data like as bellow after that we will write union query and result also i show as screenshot. So let's see bellow examle.

Users Table

Query 1

$first = DB::table('users')
            ->where('id',8);
$users = DB::table('users')
            ->where('id',2)
            ->union($first)
            ->get();

Query 2 with Model

$first = User::where('id',8);
$users = User::where('id',2)->union($first)->get();

Output :

It will help you...

# Laravel 6

# Laravel

# Laravel 7