For getting every new tutorial link Please join our telegram group

Part 12 laravel unionAll and union of two queries in query builder

If you want to see how to connect two queries with in laravel query builder than you are right place and here we also discuss difference between union vs unionAll query method.

Laravel union vs unionAll query tutorial.

  1. unoin()
  2. unionAll()
  3. unoin vs unionAll

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.

QueryException in Connection.php line 669:
SQLSTATE[21000]: Cardinality violation: 1222 The used SELECT statements have a different number of column

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);
  }

}

Laravel unoin vs unionAll

The only difference between laravel union and unionAll query is union query method remove duplicate data where unionAll not remove any duplicate data.

You read this tutorial on advanced web tuts. watch all query builder playlist click on sidebar playlist link

php laravel developer anmol sharma

Anmol Sharma

I am a software engineer and have experience in web development technologies like php, Laravel, Codeigniter, javascript, jquery, bootstrap and I like to share my deep knowledge by these blogs.

Related tutorial links