laravel/framework · error · InvalidArgumentException

Collection given to whereBelongsTo method may not be empty.

Error message

Collection given to whereBelongsTo method may not be empty.

What it means

Thrown by whereBelongsTo() when the EloquentCollection passed in (or built from a single model) contains no models. The method needs at least one related model so it can derive the relationship name from its class and build a whereIn clause against the owner key. An empty collection makes both impossible, so Laravel fails fast instead of silently producing a no-op query.

Solutions

  1. Guard the call: only invoke whereBelongsTo when the collection is non-empty ($collection->isNotEmpty()).
  2. Pass a single Model instance instead of a collection when you have exactly one related item.
  3. Filter upstream so the collection cannot reach this point empty, or branch to a no-match query (e.g. whereRaw('1=0')).

Example fix

// before
$users = User::where('active', true)->get()->filter(fn ($u) => $u->isApproved());
$query = Post::whereBelongsTo($users);

// after
$users = User::where('active', true)->get()->filter(fn ($u) => $u->isApproved());
$query = $users->isEmpty() ? Post::whereRaw('1=0') : Post::whereBelongsTo($users);
Defensive patterns

Strategy: validation

Validate before calling

// Before calling whereBelongsTo
if ($related instanceof \Illuminate\Database\Eloquent\Collection) {
    if ($related->isEmpty()) {
        // branch to a guaranteed-no-match query instead
        $query = Post::whereRaw('1 = 0');
        return $query;
    }
} elseif ($related === null) {
    throw new \InvalidArgumentException('A single Model or non-empty Collection is required.');
}

Type guard

function isNonEmptyRelated(\Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection $value): bool {
    return $value instanceof \Illuminate\Database\Eloquent\Collection ? $value->isNotEmpty() : $value->exists !== null;
}

Try / catch

try {
    $query = Post::whereBelongsTo($users);
} catch (\InvalidArgumentException $e) {
    if (str_contains($e->getMessage(), 'may not be empty')) {
        $query = Post::whereRaw('1 = 0');
    } else { throw $e; }
}

Prevention

When it happens

Trigger: Calling Post::whereBelongsTo($emptyCollection) or ->whereBelongsTo(User::all()->filter(fn($u) => false)) where the collection resolves to zero items. The first() call returns null and isEmpty() becomes true.

Common situations: Passing a collection that was filtered, searched, or paginated to zero; passing collect([]) wrapped in an EloquentCollection; chaining whereBelongsTo after a relation lookup that returns nothing; loops that build collections from optional results without checking.

Related errors


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

Appendix: source

Thrown at src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php:746

     * @param  string|null  $relationshipName
     * @param  string  $boolean
     * @return $this
     *
     * @throws \InvalidArgumentException
     * @throws \Illuminate\Database\Eloquent\RelationNotFoundException
     */
    public function whereBelongsTo($related, $relationshipName = null, $boolean = 'and')
    {
        if (! $related instanceof EloquentCollection) {
            $relatedCollection = $related->newCollection([$related]);
        } else {
            $relatedCollection = $related;

            $related = $relatedCollection->first();
        }

        if ($relatedCollection->isEmpty()) {
            throw new InvalidArgumentException('Collection given to whereBelongsTo method may not be empty.');
        }

        if ($relationshipName === null) {
            $relationshipName = Str::camel(class_basename($related));
        }

        try {
            $relationship = $this->model->{$relationshipName}();
        } catch (BadMethodCallException) {
            throw RelationNotFoundException::make($this->model, $relationshipName);
        }

        if (! $relationship instanceof BelongsTo) {
            throw RelationNotFoundException::make($this->model, $relationshipName, BelongsTo::class);
        }

        $this->whereIn(
            $relationship->getQualifiedForeignKeyName(),

View on GitHub (pinned to e0f6eb3518)