Laravel unoin() query
Laravel union query method is use for connect two different queries that are get data by different tables and it remove duplicate data. Union method is use in big projects where we require to get more tables data with. It connect two queries that select same name columns else it give this error.
Example of laravel union method
Example 1 union two queries that select same table data
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class EmployeeController extends Controller{
public function index(){
$managers = DB::table('employees')->where('role','manager');
$employees = DB::table('employees')->where('salary','>','10000')->union($managers)->get();
dd($employees);
}
}
Example 2 union two queries that select different table data
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class EmployeeController extends Controller{
public function index(){
$users = DB::table('users')->select('users.name','users.email','users.phone');
$employees = DB::table('employees')->select('employees.name','employees.email','employees.phone')
->union($users)->get();
dd($employees);
}
}
Laravel unionAll() method
Laravel query builder use unionAll() method for connecting two DB queries unionAll method work same as union method and it not remove duplicate data.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class EmployeeController extends Controller{
public function index(){
$users = DB::table('users')->select('users.name','users.email','users.phone');
$employees = DB::table('employees')->select('employees.name','employees.email','employees.phone')
->unionAll($users)->get();
dd($employees);
}
}
===========================================================
Another Solution
$posts = DB::table('posts')->select('id', 'title', 'body');
$comments = DB::table('comments')->select('id', 'post_id', 'comment');
$unionedQuery = $posts->union($comments);
$distinctQuery = $unionedQuery->distinct();
$results = $distinctQuery->get();
Top comments (0)