{"id":"2fdfb237501ed300","repo":"laravel/framework","slug":"collection-given-to-wherebelongsto-method-may-not","errorCode":null,"errorMessage":"Collection given to whereBelongsTo method may not be empty.","messagePattern":"Collection given to whereBelongsTo method may not be empty\\.","errorType":"exception","errorClass":"InvalidArgumentException","httpStatus":null,"severity":"error","filePath":"src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php","lineNumber":746,"sourceCode":"     * @param  string|null  $relationshipName\n     * @param  string  $boolean\n     * @return $this\n     *\n     * @throws \\InvalidArgumentException\n     * @throws \\Illuminate\\Database\\Eloquent\\RelationNotFoundException\n     */\n    public function whereBelongsTo($related, $relationshipName = null, $boolean = 'and')\n    {\n        if (! $related instanceof EloquentCollection) {\n            $relatedCollection = $related->newCollection([$related]);\n        } else {\n            $relatedCollection = $related;\n\n            $related = $relatedCollection->first();\n        }\n\n        if ($relatedCollection->isEmpty()) {\n            throw new InvalidArgumentException('Collection given to whereBelongsTo method may not be empty.');\n        }\n\n        if ($relationshipName === null) {\n            $relationshipName = Str::camel(class_basename($related));\n        }\n\n        try {\n            $relationship = $this->model->{$relationshipName}();\n        } catch (BadMethodCallException) {\n            throw RelationNotFoundException::make($this->model, $relationshipName);\n        }\n\n        if (! $relationship instanceof BelongsTo) {\n            throw RelationNotFoundException::make($this->model, $relationshipName, BelongsTo::class);\n        }\n\n        $this->whereIn(\n            $relationship->getQualifiedForeignKeyName(),","sourceCodeStart":728,"sourceCodeEnd":764,"githubUrl":"https://github.com/laravel/framework/blob/bd6b5437e6ad87bb49f9b426724f07a9f64e9683/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php#L728-L764","documentation":"Thrown by Eloquent's whereBelongsTo query scope when the EloquentCollection passed as the related argument is empty. The method needs at least one model to derive the relationship name (via class basename) and to pluck owner keys for the whereIn clause, so an empty collection is unrecoverable. It is an InvalidArgumentException signaling a caller bug rather than a data condition.","triggerScenarios":"Calling User::whereBelongsTo($emptyCollection) or ->orWhereBelongsTo($emptyCollection) where $emptyCollection is an EloquentCollection with zero items (e.g. collecting related models from another query that returned no rows).","commonSituations":"Passing the result of a ->get() or ->all() that may legitimately be empty (e.g. filtering by a team/role list that no user belongs to), or building a collection conditionally that ends up empty before the scope call.","solutions":["Guard the call: only invoke whereBelongsTo when the collection is non-empty (if ($collection->isNotEmpty())).","Pass a single Model instance instead of a collection when you only have one related model.","Early-return or fall back to a no-op query (e.g. whereRaw('1=0')) when the input collection is empty so the intent (match nothing) is preserved."],"exampleFix":"// before\nUser::whereBelongsTo($teams)->get();  // $teams may be empty\n\n// after\nUser::when($teams->isNotEmpty(), fn ($q) => $q->whereBelongsTo($teams))->get();","handlingStrategy":"validation","validationCode":"if ($related instanceof \\Illuminate\\Database\\Eloquent\\Collection && $related->isEmpty()) {\n    // skip or return empty result instead of calling whereBelongsTo\n    return User::whereRaw('1=0')->get();\n}\nUser::whereBelongsTo($related)->get();","typeGuard":"function hasRelatedModels($related): bool {\n    return $related instanceof \\Illuminate\\Database\\Eloquent\\Model\n        || ($related instanceof \\Illuminate\\Database\\Eloquent\\Collection && $related->isNotEmpty());\n}","tryCatchPattern":"try {\n    User::whereBelongsTo($related)->get();\n} catch (\\InvalidArgumentException $e) {\n    if (str_contains($e->getMessage(), 'may not be empty')) {\n        return collect();\n    }\n    throw $e;\n}","preventionTips":["Always validate collection emptiness before relationship-scope calls.","Prefer passing a single Model when you only have one related entity.","Wrap the call in when($collection->isNotEmpty(), ...) to make the clause conditional."],"tags":["eloquent","query-builder","relationships","validation"],"analyzedSha":"bd6b5437e6ad87bb49f9b426724f07a9f64e9683","analyzedAt":"2026-08-06T00:28:32.783Z","schemaVersion":2}