{"record":{"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/e0f6eb3518ac29fbbca8529e97d0df7fc9f24481/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php#L728-L764","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Guard the call: only invoke whereBelongsTo when the collection is non-empty ($collection->isNotEmpty()).","Pass a single Model instance instead of a collection when you have exactly one related item.","Filter upstream so the collection cannot reach this point empty, or branch to a no-match query (e.g. whereRaw('1=0'))."],"exampleFix":"// before\n$users = User::where('active', true)->get()->filter(fn ($u) => $u->isApproved());\n$query = Post::whereBelongsTo($users);\n\n// after\n$users = User::where('active', true)->get()->filter(fn ($u) => $u->isApproved());\n$query = $users->isEmpty() ? Post::whereRaw('1=0') : Post::whereBelongsTo($users);","handlingStrategy":"validation","validationCode":"// Before calling whereBelongsTo\nif ($related instanceof \\Illuminate\\Database\\Eloquent\\Collection) {\n    if ($related->isEmpty()) {\n        // branch to a guaranteed-no-match query instead\n        $query = Post::whereRaw('1 = 0');\n        return $query;\n    }\n} elseif ($related === null) {\n    throw new \\InvalidArgumentException('A single Model or non-empty Collection is required.');\n}","typeGuard":"function isNonEmptyRelated(\\Illuminate\\Database\\Eloquent\\Model|\\Illuminate\\Database\\Eloquent\\Collection $value): bool {\n    return $value instanceof \\Illuminate\\Database\\Eloquent\\Collection ? $value->isNotEmpty() : $value->exists !== null;\n}","tryCatchPattern":"try {\n    $query = Post::whereBelongsTo($users);\n} catch (\\InvalidArgumentException $e) {\n    if (str_contains($e->getMessage(), 'may not be empty')) {\n        $query = Post::whereRaw('1 = 0');\n    } else { throw $e; }\n}","preventionTips":["Always filter upstream so the collection reaching whereBelongsTo is guaranteed non-empty.","When the related set is user-selected (UI), branch to a no-match query when zero items are chosen.","Prefer passing a single Model when you only have one - it short-circuits the empty check."],"tags":["eloquent","relationships","belongs-to","query-builder","validation"],"backgroundTag":null,"analyzedSha":"e0f6eb3518ac29fbbca8529e97d0df7fc9f24481","analyzedAt":"2026-08-11T20:52:37.562Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}