How to Implement Unions with Query Builder in Laravel?

You can easily join the result of two queries using Laravel Query builder. We have union() and unionAll() methods for this purpose. Here is the sample of union() method with a very simple syntax. Remember we are using get() method after second one or  the last one as that will be our final query.

$noStatusLeads = DB::table( 'leads' )->whereNull( 'status' );
$noStatusAndEmailLeads = DB::table( 'leads' )
                       ->whereNull( 'email' )
                       ->union( $noStatusLeads )
                       ->get();

And unionAll() will be like this. The union() will remove duplicate records from selection but unionAll() will include duplicate records too.

$noStatusAndEmailLeads = DB::table( 'leads' )
                       ->whereNull( 'email' )
                       ->unionAll( $noStatusLeads )
                       ->get();

I hope now union makes sense to you in Laravel Query builder. If you have any problem please feel free to comment. We appreciate that.