{"id":"278aec7758b65da3","repo":"laravel/framework","slug":"collection-given-to-wheremorphedto-method-may-not","errorCode":null,"errorMessage":"Collection given to whereMorphedTo method may not be empty.","messagePattern":"Collection given to whereMorphedTo method may not be empty\\.","errorType":"exception","errorClass":"InvalidArgumentException","httpStatus":null,"severity":"error","filePath":"src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php","lineNumber":644,"sourceCode":"\n        if (is_null($model)) {\n            return $this->whereNull($relation->qualifyColumn($relation->getMorphType()), $boolean);\n        }\n\n        if (is_string($model)) {\n            $morphMap = Relation::morphMap();\n\n            if (! empty($morphMap) && in_array($model, $morphMap)) {\n                $model = array_search($model, $morphMap, true);\n            }\n\n            return $this->where($relation->qualifyColumn($relation->getMorphType()), $model, null, $boolean);\n        }\n\n        $models = BaseCollection::wrap($model);\n\n        if ($models->isEmpty()) {\n            throw new InvalidArgumentException('Collection given to whereMorphedTo method may not be empty.');\n        }\n\n        return $this->where(function ($query) use ($relation, $models) {\n            $models->groupBy(fn ($model) => $model->getMorphClass())->each(function ($models) use ($query, $relation) {\n                $query->orWhere(function ($query) use ($relation, $models) {\n                    $query->where($relation->qualifyColumn($relation->getMorphType()), $models->first()->getMorphClass())\n                        ->whereIn($relation->qualifyColumn($relation->getForeignKeyName()), $models->map->getKey());\n                });\n            });\n        }, null, null, $boolean);\n    }\n\n    /**\n     * Add a not morph-to relationship condition to the query.\n     *\n     * @param  \\Illuminate\\Database\\Eloquent\\Relations\\MorphTo<*, *>|string  $relation\n     * @param  \\Illuminate\\Database\\Eloquent\\Model|iterable<int, \\Illuminate\\Database\\Eloquent\\Model>|string  $model\n     * @return $this","sourceCodeStart":626,"sourceCodeEnd":662,"githubUrl":"https://github.com/laravel/framework/blob/bd6b5437e6ad87bb49f9b426724f07a9f64e9683/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php#L626-L662","documentation":"whereMorphedTo() builds a WHERE morph_type = X AND morph_id IN (...) clause from the supplied models. An empty collection produces no group-by bucket and cannot express a meaningful condition, so the framework rejects it with InvalidArgumentException rather than generating a no-op (always-false) query.","triggerScenarios":"Calling $query->whereMorphedTo('commentable', collect([])) (or []), typically because an upstream filter that was supposed to supply models returned nothing.","commonSituations":"Dynamic filters where the user selected zero items; collections built from optional request inputs that resolved to empty; looping over grouped data where a group is legitimately empty.","solutions":["Guard for emptiness before calling: if ($models->isNotEmpty()) { $query->whereMorphedTo(...); }.","When the intent is 'match nothing', use whereRaw('1=0') or skip applying the filter explicitly.","Pass null (matches NULL morph_type) or a single model instead of an empty collection where semantics allow."],"exampleFix":"// before\n$query->whereMorphedTo('commentable', $selectedModels); // could be empty\n\n// after\nif ($selectedModels->isNotEmpty()) {\n    $query->whereMorphedTo('commentable', $selectedModels);\n}","handlingStrategy":"validation","validationCode":"$models = \\Illuminate\\Support\\Collection::wrap($model);\nif ($models->isEmpty()) {\n    // decide: skip filter, or throw a domain-level exception\n    return $query;\n}\nreturn $query->whereMorphedTo($relation, $models);","typeGuard":"function hasMorphModels(mixed $model): bool\n{\n    return ! \\Illuminate\\Support\\Collection::wrap($model)->isEmpty();\n}","tryCatchPattern":"try {\n    return $query->whereMorphedTo($relation, $models);\n} catch (\\InvalidArgumentException $e) {\n    if (str_contains($e->getMessage(), 'may not be empty')) {\n        return $query; // no filter applied\n    }\n    throw $e;\n}","preventionTips":["Guard with isNotEmpty() before calling whereMorphedTo().","Build the model list upstream from validated request inputs so emptiness is intentional.","Write a test covering the empty-input branch."],"tags":["eloquent","morph-query","validation","polymorphic"],"analyzedSha":"bd6b5437e6ad87bb49f9b426724f07a9f64e9683","analyzedAt":"2026-08-06T00:28:32.783Z","schemaVersion":2}