How To Use Union Queries Statement With Example In Laravel

admin_img Posted By Bajarangi soft , Posted On 23-09-2020

The query builder may also be used to write join statements. To perform a basic "join", you may use the join method on a query builder instance. The first argument passed to the join method is the name of the table you need to join to, while the remaining arguments specify the column constraints for the join.Laravel provide query builder and they give us join, relationship, subquery and also union. But we need some time to get all records from two different table at same time you need to use union.

How to Use Union Queries In Laravel

Unions
The query builder also provides a quick way to "union" two queries together. For example, you may create an initial query and use the union method to union it with a second query:

Example(1)

app/Http/Controllers/UnionTableController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;

class UnoinTableController extends Controller
{
    function index()
    {

        $first = DB::table('users') ->whereNull('first_name');
        $users = DB::table('users') ->whereNull('last_name') ->union($first) ->get();
        return view('user.index', ['users' => $users]);
    }
}
?>

selecting data which have  null values in first_name column and last_name column and return data from controller to index.blade.php file

resources/views/user/index.blade.php
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title> Use Union Queries In Laravel</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <br />
    <h3 align="center"> Use Union Queries In Laravel</h3>
    <br />
    <div class="table-responsive">
        <table class="table table-bordered table-striped">
            <thead>
            <tr>
                <th>First Name</th>
                <th>Last Name</th>
            </tr>
            </thead>
            <tbody>
            @foreach($users as $row)
            <tr>
                <td>{{ $row->first_name }}</td>
                <td>{{ $row->last_name }}</td>
            </tr>
            @endforeach
            </tbody>
        </table>
    </div>
</div>
</body>
</html>
 

routes/web.php

Route::get('SubqueryJoin', 'SubqueryJoinTableController@index');

Related Post