diff --git a/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php b/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php index f3a50501fdd6..6cfb5579c059 100755 --- a/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php +++ b/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php @@ -6,6 +6,7 @@ use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\Concerns\InteractsWithDictionary; +use InvalidArgumentException; abstract class HasOneOrMany extends Relation { @@ -175,6 +176,7 @@ protected function getRelationValue(array $dictionary, $key, $type) * Build model dictionary keyed by the relation's foreign key. * * @param \Illuminate\Database\Eloquent\Collection $results + * @throws \InvalidArgumentException * @return array */ protected function buildDictionary(Collection $results) @@ -182,6 +184,10 @@ protected function buildDictionary(Collection $results) $foreign = $this->getForeignKeyName(); return $results->mapToDictionary(function ($result) use ($foreign) { + if (! isset($result->{$foreign})) { + throw new InvalidArgumentException('Relation needs foreign key "'.$result->qualifyColumn($foreign).'" to be fetched'); + } + return [$this->getDictionaryKey($result->{$foreign}) => $result]; })->all(); } diff --git a/src/Illuminate/Database/Eloquent/Relations/Relation.php b/src/Illuminate/Database/Eloquent/Relations/Relation.php index 7fe9f3e9fa82..9ef19bef434d 100755 --- a/src/Illuminate/Database/Eloquent/Relations/Relation.php +++ b/src/Illuminate/Database/Eloquent/Relations/Relation.php @@ -12,6 +12,7 @@ use Illuminate\Support\Arr; use Illuminate\Support\Traits\ForwardsCalls; use Illuminate\Support\Traits\Macroable; +use InvalidArgumentException; /** * @mixin \Illuminate\Database\Eloquent\Builder @@ -262,11 +263,16 @@ public function getRelationCountHash($incrementJoinCount = true) * * @param array $models * @param string|null $key + * @throws \InvalidArgumentException * @return array */ protected function getKeys(array $models, $key = null) { return collect($models)->map(function ($value) use ($key) { + if (! isset($value->{$key})) { + throw new InvalidArgumentException('Relation needs parent key "'.$value->qualifyColumn($key).'" to be fetched'); + } + return $key ? $value->getAttribute($key) : $value->getKey(); })->values()->unique(null, true)->sort()->all(); }