{"record":{"id":"1c79391aa8b95d5a","repo":"laravel/framework","slug":"collection-given-to-whereattachedto-method-may-not","errorCode":null,"errorMessage":"Collection given to whereAttachedTo method may not be empty.","messagePattern":"Collection given to whereAttachedTo method may not be empty\\.","errorType":"exception","errorClass":"InvalidArgumentException","httpStatus":null,"severity":"error","filePath":"src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php","lineNumber":802,"sourceCode":"    /**\n     * Add a \"belongs to many\" relationship where clause to the query.\n     *\n     * @param  \\Illuminate\\Database\\Eloquent\\Model|\\Illuminate\\Database\\Eloquent\\Collection<int, \\Illuminate\\Database\\Eloquent\\Model>  $related\n     * @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 whereAttachedTo($related, $relationshipName = null, $boolean = 'and')\n    {\n        $relatedCollection = $related instanceof EloquentCollection ? $related : $related->newCollection([$related]);\n\n        $related = $relatedCollection->first();\n\n        if ($relatedCollection->isEmpty()) {\n            throw new InvalidArgumentException('Collection given to whereAttachedTo method may not be empty.');\n        }\n\n        if ($relationshipName === null) {\n            $relationshipName = Str::plural(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 BelongsToMany) {\n            throw RelationNotFoundException::make($this->model, $relationshipName, BelongsToMany::class);\n        }\n\n        $this->has(\n            $relationshipName,","sourceCodeStart":784,"sourceCodeEnd":820,"githubUrl":"https://github.com/laravel/framework/blob/e0f6eb3518ac29fbbca8529e97d0df7fc9f24481/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php#L784-L820","documentation":"Thrown by whereAttachedTo() when the supplied EloquentCollection (or collection built from a single model) is empty. Like whereBelongsTo, this method needs at least one related model to resolve the belongsToMany relationship name and to build the matching sub-query. An empty input is treated as a programmer error rather than an empty filter.","triggerScenarios":"Calling Post::whereAttachedTo($emptyTagCollection) or ->whereAttachedTo(Tag::where('name', 'nonexistent')->get()) where the collection has no models. The method always builds a collection first, then checks isEmpty().","commonSituations":"Filtering tags/categories to none before passing them in; passing a collection from an optional relation that resolved to nothing; UI where a user selects zero items then submits.","solutions":["Check the collection is non-empty before calling whereAttachedTo.","Branch to a no-match query (e.g. whereRaw('1=0')) when the collection is empty.","Pass a single Model instance when only one related item is involved."],"exampleFix":"// before\n$tags = Tag::whereIn('slug', $request->input('tags', []))->get();\n$query = Post::whereAttachedTo($tags);\n\n// after\n$tags = Tag::whereIn('slug', $request->input('tags', []))->get();\n$query = $tags->isEmpty() ? Post::whereRaw('1=0') : Post::whereAttachedTo($tags);","handlingStrategy":"validation","validationCode":"if ($related instanceof \\Illuminate\\Database\\Eloquent\\Collection && $related->isEmpty()) {\n    return Post::whereRaw('1 = 0'); // no rows match an empty attachment set\n}","typeGuard":"function hasAttachedItems(\\Illuminate\\Database\\Eloquent\\Collection $c): bool {\n    return $c->isNotEmpty();\n}","tryCatchPattern":"try {\n    $query = Post::whereAttachedTo($tags);\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":["Validate that at least one tag/category was selected in the request before calling whereAttachedTo.","Wrap user-driven filtering with an explicit empty check.","Use the same non-empty guard pattern as whereBelongsTo."],"tags":["eloquent","relationships","belongs-to-many","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"}