{"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/bd6b5437e6ad87bb49f9b426724f07a9f64e9683/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php#L784-L820","documentation":"Thrown by whereAttachedTo (the BelongsToMany analog of whereBelongsTo) when the passed EloquentCollection is empty. The method resolves the relationship name from the first element and uses its keys for a whereIn, so an empty collection cannot be processed. It is an InvalidArgumentException indicating a misuse of the API.","triggerScenarios":"Calling User::whereAttachedTo($emptyCollection) where the collection represents tags/roles/etc. to filter by attachment, but the collection contains no models.","commonSituations":"Filtering a many-to-many relation by a list of related models that a previous query produced empty (e.g. filtering posts by tags when no tags match a prior search).","solutions":["Check the collection is non-empty before calling whereAttachedTo (if ($collection->isNotEmpty())).","Wrap with when() to make the clause conditional on non-empty input.","Fall back to a deliberately empty result set when the intent is 'match nothing'."],"exampleFix":"// before\nPost::whereAttachedTo($tags)->get();\n\n// after\nPost::when($tags->isNotEmpty(), fn ($q) => $q->whereAttachedTo($tags))->get();","handlingStrategy":"validation","validationCode":"if ($related instanceof \\Illuminate\\Database\\Eloquent\\Collection && $related->isEmpty()) {\n    return Post::whereRaw('1=0')->get();\n}\nPost::whereAttachedTo($related)->get();","typeGuard":"function hasAttachedModels($related): bool {\n    return $related instanceof \\Illuminate\\Database\\Eloquent\\Model\n        || ($related instanceof \\Illuminate\\Database\\Eloquent\\Collection && $related->isNotEmpty());\n}","tryCatchPattern":"try {\n    Post::whereAttachedTo($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":["Validate the related collection is non-empty before whereAttachedTo.","Use when($tags->isNotEmpty(), fn ($q) => $q->whereAttachedTo($tags)) to make it safe.","Fall back to a no-match query when the intent is 'match nothing'."],"tags":["eloquent","query-builder","relationships","belongs-to-many","validation"],"analyzedSha":"bd6b5437e6ad87bb49f9b426724f07a9f64e9683","analyzedAt":"2026-08-06T00:28:32.783Z","schemaVersion":2}