laravel/framework · error · LogicException

Unable to create query for empty collection.

Error message

Unable to create query for empty collection.

What it means

Thrown by Eloquent\Collection::toQuery() when the collection is empty. toQuery() builds an Eloquent query builder scoped to the models in the collection via whereKey($this->modelKeys()); with no first() element there is no model to derive a newModelQuery() from, so Laravel refuses rather than guess a class.

Solutions

  1. Guard the call: if ($collection->isNotEmpty()) { $collection->toQuery(); }.
  2. Build the query up-front from the builder instead of round-tripping through a collection (e.g. keep the Builder and add whereKey()).
  3. If you need a query for an empty set, instantiate the model query explicitly: User::query()->whereKey([]).

Example fix

// before
$collection = User::where('active', false)->get();
$collection->toQuery(); // LogicException when empty

// after
if ($collection->isNotEmpty()) {
    $collection->toQuery()->update(['flagged' => true]);
}
Defensive patterns

Strategy: validation

Validate before calling

if ($collection->isEmpty()) {
    // nothing to query; handle gracefully
    return;
}
$query = $collection->toQuery();

Type guard

function isNonEmpty(\Illuminate\Support\Collection $c): bool
{
    return $c->isNotEmpty();
}

Prevention

When it happens

Trigger: Calling $collection->toQuery() on a collection that returned zero results from a query (e.g. User::where('active', false)->get()->toQuery()), or calling toQuery() on a freshly new-upped collection with no items.

Common situations: Chaining toQuery() after a filter that may yield zero rows; calling toQuery() inside a loop where some iterations produce empty collections; refactoring a loop that assumed at least one result.

Related errors


AI-assisted analysis of laravel/framework@e0f6eb3518 (2026-08-11). Data as JSON: /api/errors/5df98d4c7e01e9a4. Report an issue: GitHub.

Appendix: source

Thrown at src/Illuminate/Database/Eloquent/Collection.php:935

            }
        });

        return $connection;
    }

    /**
     * Get the Eloquent query builder from the collection.
     *
     * @return \Illuminate\Database\Eloquent\Builder<TModel>
     *
     * @throws \LogicException
     */
    public function toQuery()
    {
        $model = $this->first();

        if (! $model) {
            throw new LogicException('Unable to create query for empty collection.');
        }

        $class = get_class($model);

        if ($this->contains(fn ($model) => ! $model instanceof $class)) {
            throw new LogicException('Unable to create query for collection with mixed types.');
        }

        return $model->newModelQuery()->whereKey($this->modelKeys());
    }
}

View on GitHub (pinned to e0f6eb3518)