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]);
}
}
?>
<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');