To apply a `where()` or `whereNull()` filter to the **entire result of a Laravel UNION**, wrap the union in a derived-table query with `fromSub()` and put the filter on the outer query. Calling `whereNull()` after `union()` on the original Eloquent builder does not create an outer `WHERE`: it generally adds the condition to the first SELECT. You do not need to build the whole query with `selectRaw()`.
This matters when two models produce the same search-result columns and you want to apply one reusable set of filters, ordering rules and pagination to both.
Why whereNull() filters only the first UNION branch
Consider the following Laravel code:
$results = EntityMember::query()
->union(User::query()->select(/* matching columns */))
->whereNull('user_id')
->get();Laravel's query builder retains the first SELECT as the main query. The union is a separate part of the query definition. Adding a standard `whereNull()` to that same builder modifies its main SELECT, not a new query surrounding the union.
Conceptually, the SQL becomes:
SELECT id, user_id, name FROM entity_members
WHERE user_id IS NULL
UNION
SELECT id, manager_id AS user_id, name FROM users;The condition does not apply to rows from `users`. Adding another `whereNull()` inside the second query would work, but it means duplicating filters, which becomes awkward when separate service classes construct the two branches.
The intended structure is a SELECT **from the combined result**:
SELECT *
FROM (
SELECT id, user_id, name FROM entity_members
UNION ALL
SELECT id, manager_id AS user_id, name FROM users
) AS combined
WHERE combined.user_id IS NULL;The outer `WHERE` sees the output of both queries. This is exactly what Laravel's `fromSub()` method is designed to express.
1. Build a UNION with matching columns
Each SELECT in a union must return the same number of columns in corresponding positions, with compatible types. The following example assumes `entity_members` has `id`, `user_id` and `name`, while `users` has `id`, `manager_id` and `name`. Here, `manager_id` is an **illustrative** field mapped to the shared output name `user_id`; replace it with the appropriate field or expression from your actual schema.
<?php
use App\Models\EntityMember;
use App\Models\User;
$members = EntityMember::query()
->select([
'entity_members.id as id',
'entity_members.user_id as user_id',
'entity_members.name as name',
])
->selectRaw("'member' as source_type");
$users = User::query()
->select([
'users.id as id',
'users.manager_id as user_id',
'users.name as name',
])
->selectRaw("'user' as source_type");
$combined = $members->unionAll($users);The `source_type` literals are fixed strings defined by the developer, not user input. They let the application distinguish a member record from a user record even when both tables have the same numeric ID.
Avoid `SELECT *` in this situation. A specific projection makes column names, order and mapping explicit. It also prevents an added column in one table from silently breaking the union later.
2. Apply filters to the entire UNION with fromSub()
Use a fresh database query builder for the outer query:
<?php
use Illuminate\Support\Facades\DB;
$results = DB::query()
->fromSub($combined, 'combined')
->whereNull('combined.user_id')
->orderBy('combined.name')
->get();The generated SQL has the same overall shape as:
SELECT *
FROM (
SELECT id, user_id, name, 'member' AS source_type
FROM entity_members
UNION ALL
SELECT id, manager_id AS user_id, name, 'user' AS source_type
FROM users
) AS combined
WHERE combined.user_id IS NULL
ORDER BY combined.name;`fromSub()` accepts a Laravel query builder and handles the subquery's SQL and parameter bindings. You do not need to concatenate an SQL string yourself.
The alias `combined` gives the derived table a name that can be used in outer `WHERE` and `ORDER BY` expressions.
This approach returns a collection of ordinary result objects rather than hydrated `EntityMember` models. For reporting, searches and read-only listings, that is often the simplest design.
3. Complete Laravel controller example
The following action returns filtered, combined results as JSON. Put it in an existing Laravel controller with the correct namespace for your application. Both models and the illustrative columns described above must exist.
<?php
namespace App\Http\Controllers;
use App\Models\EntityMember;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
class CombinedPeopleController extends Controller
{
public function index(): JsonResponse
{
$members = EntityMember::query()
->select([
'entity_members.id as id',
'entity_members.user_id as user_id',
'entity_members.name as name',
])
->selectRaw("'member' as source_type");
$users = User::query()
->select([
'users.id as id',
'users.manager_id as user_id',
'users.name as name',
])
->selectRaw("'user' as source_type");
$combined = $members->unionAll($users);
$rows = DB::query()
->fromSub($combined, 'combined')
->whereNull('combined.user_id')
->orderBy('combined.name')
->get();
return response()->json($rows);
}
}For example, if an entity member named Ada has a null `user_id` and a user named Cara has a null `manager_id`, both can appear in the result. Records from either branch with non-null mapped values are filtered out.
Because the example uses the query builder, it does not depend on Eloquent model hydration to represent two different entity types.
4. Keep a custom Eloquent builder and its filter methods
Sometimes you cannot switch to `DB::query()`. Your project might define a custom `EntityMemberBuilder` containing reusable methods such as `withoutLinkedUser()` or `activeOnly()`. You want to continue calling those methods on the outer query.
You can do that by creating a **new EntityMember Eloquent builder** and calling `fromSub()` on that builder:
<?php
$combined = $members->unionAll($users);
$results = EntityMember::query()
->fromSub($combined, 'entity_members')
->withoutLinkedUser()
->orderBy('entity_members.name')
->get();Here `withoutLinkedUser()` is a custom method shown below; it is not a built-in Laravel method.
<?php
namespace App\Builders;
use Illuminate\Database\Eloquent\Builder;
class EntityMemberBuilder extends Builder
{
public function withoutLinkedUser(): static
{
return $this->whereNull('entity_members.user_id');
}
}The model must already be configured to return that custom builder:
<?php
namespace App\Models;
use App\Builders\EntityMemberBuilder;
use Illuminate\Database\Eloquent\Model;
class EntityMember extends Model
{
protected $table = 'entity_members';
public function newEloquentBuilder($query): EntityMemberBuilder
{
return new EntityMemberBuilder($query);
}
}`fromSub()` is implemented on Laravel's underlying query builder and can be forwarded through Eloquent's builder. Because it is called on the fresh `EntityMember::query()` instance, the custom Eloquent builder remains available for subsequent filters.
**The alias is significant.** If an existing custom filter qualifies fields as `entity_members.user_id`, the outer derived table must use the same alias, or that filter needs to be updated to reference the new alias.
Be careful with Eloquent global scopes, including soft-delete scopes: if they refer to columns such as `entity_members.deleted_at`, those columns must exist in the derived-table output or the scope must be handled deliberately. Check the generated SQL before relying on this technique in an application with several model scopes.
5. Do not treat mixed UNION rows as ordinary model records
When the outer query uses `EntityMember::query()`, Eloquent hydrates the combined rows as `EntityMember` objects, even when a row originated from `users`.
That can be convenient for reusing read-only filtering methods, but it does **not** turn a user into a real entity-member record. IDs can overlap between source tables; relationships, mutators and model methods may assume the wrong source.
Do not call `save()`, `delete()` or other model write methods on these synthetic results. Prefer a dedicated read model, data transfer object or `DB::query()` if the result set represents genuinely different entity types.
6. UNION versus UNION ALL
Laravel exposes both `union()` and `unionAll()`:
<?php
$combined = $members->union($users); // Removes identical rows.
$combined = $members->unionAll($users); // Preserves all rows.`UNION` removes duplicate rows based on the **complete selected row**; `UNION ALL` retains them. If your application needs both source records even when their selected values match, use `unionAll()`.
In the example above, the fixed `source_type` column also helps identify each source. However, it does not replace a proper record identity policy if you later merge, paginate or update records.
The correct operator depends on whether duplicate elimination is part of the business requirement, not simply whether the two source tables are different.
7. Pagination, ordering and performance
Apply overall ordering and pagination to the **outer** query, not just one union branch:
<?php
$page = DB::query()
->fromSub($combined, 'combined')
->whereNull('combined.user_id')
->orderBy('combined.name')
->orderBy('combined.source_type')
->orderBy('combined.id')
->paginate(25);For reliable pagination, use an ordering that uniquely distinguishes rows. If `(source_type, id)` is unique in the combined output, it can serve as a stable tie-breaker after sorting by name. Apply any search filters before calling `paginate()`.
A derived table is not automatically the fastest plan on every database. Query optimisers may push outer conditions into union branches, but that depends on the database and the query. Use `EXPLAIN` to inspect real execution plans. For large datasets, applying the same selective condition separately inside each branch may outperform an outer filter, even though it requires more coordination in application code.
8. Debug the generated SQL and bindings
Before assuming Eloquent applies a condition where you intended, inspect the query:
<?php
$query = DB::query()
->fromSub($combined, 'combined')
->whereNull('combined.user_id');
logger()->debug('Combined query', [
'sql' => $query->toSql(),
'bindings' => $query->getBindings(),
]);`toSql()` shows placeholders instead of interpolating values, and `getBindings()` shows the associated values. Avoid logging bindings if they contain credentials or personal information.
Test with a record from each branch that should pass and another from each branch that should fail. That proves the filter applies to the combined result instead of only one SELECT.
Final recommendation
Use `DB::query()->fromSub($union, 'combined')` when you want a straightforward read-only result set from two models. If you must retain a custom Eloquent builder, create a fresh model builder and call `fromSub()` on **that instance**, using an alias compatible with the custom scopes.
Explicitly align the selected columns, choose `union()` or `unionAll()` according to duplicate-handling requirements, and apply shared filtering, sorting and pagination to the outer query. You can do all of this with Laravel's query builder without writing the union as a raw SQL string.
For reference, see the Laravel query builder guide and the Laravel Query Builder fromSub API.
