From 902be20795c141514e0170fa66624cd5a6745798 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=A2=E5=9B=BD=E7=A5=A5?= Date: Sat, 10 Oct 2026 20:53:11 +0800 Subject: [PATCH] Fixed PHP 8.1 deprecation warnings for null array offset in `BelongsTo` and `MorphTo` relationships. --- src/Model/Relations/BelongsTo.php | 14 +++++++++++--- src/Model/Relations/MorphTo.php | 10 ++++++++-- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/src/Model/Relations/BelongsTo.php b/src/Model/Relations/BelongsTo.php index 67c6c6a..5ae3416 100755 --- a/src/Model/Relations/BelongsTo.php +++ b/src/Model/Relations/BelongsTo.php @@ -152,15 +152,23 @@ public function match(array $models, Collection $results, $relation) $dictionary = []; foreach ($results as $result) { - $dictionary[$result->getAttribute($owner)] = $result; + // The owner key can be null when not selected; null as an array offset is deprecated since PHP 8.1 + $key = $result->getAttribute($owner); + + if ($key !== null) { + $dictionary[$key] = $result; + } } // Once we have the dictionary constructed, we can loop through all the parents // and match back onto their children using these keys of the dictionary and // the primary key of the children to map them onto the correct instances. foreach ($models as $model) { - if (isset($dictionary[$model->{$foreign}])) { - $model->setRelation($relation, $dictionary[$model->{$foreign}]); + // The foreign key is nullable, and using null as an array offset is deprecated since PHP 8.1 + $key = $model->{$foreign}; + + if ($key !== null && isset($dictionary[$key])) { + $model->setRelation($relation, $dictionary[$key]); } } diff --git a/src/Model/Relations/MorphTo.php b/src/Model/Relations/MorphTo.php index b569e26..1a2cae2 100644 --- a/src/Model/Relations/MorphTo.php +++ b/src/Model/Relations/MorphTo.php @@ -245,9 +245,15 @@ public function morphWith(array $with) protected function buildDictionary(Collection $models) { foreach ($models as $model) { - if ($model->{$this->morphType}) { - $this->dictionary[$model->{$this->morphType}][$model->{$this->foreignKey}][] = $model; + // Both are nullable, and using null as an array offset is deprecated since PHP 8.1 + $type = $model->{$this->morphType}; + $key = $model->{$this->foreignKey}; + + if (empty($type) || $key === null) { + continue; } + + $this->dictionary[$type][$key][] = $model; } }