Skip to content

[12.x] Fix null array key deprecation in HasOneOrMany relation matching#58191

Merged
taylorotwell merged 1 commit into
laravel:12.xfrom
serhiilabs:fix/php85-null-array-key-deprecation
Dec 22, 2025
Merged

[12.x] Fix null array key deprecation in HasOneOrMany relation matching#58191
taylorotwell merged 1 commit into
laravel:12.xfrom
serhiilabs:fix/php85-null-array-key-deprecation

Conversation

@serhiilabs

Copy link
Copy Markdown
Contributor

Summary

This PR fixes the PHP 8.5+ deprecation warning "Using null as an array offset is deprecated" in HasOneOrMany, HasManyThrough, and HasOneThrough relations.

More importantly, it fixes a behavioral bug: models with null local key values were incorrectly matching records with empty string ('') foreign keys due to PHP's implicit null'' conversion.

Problem

class Category extends Model
{
    public function children(): HasMany
    {
        return $this->hasMany(self::class, 'parent_guid', 'guid');
    }
}

// Categories with null guid incorrectly get children with '' parent_guid
Category::with('children')->get();

Solution

$key = $this->getDictionaryKey($model->getAttribute($this->localKey));

if ($key !== null && isset($dictionary[$key])) {

Skip dictionary lookup when key is null.

Test

Added test verifying models with null local key don't receive related records.

Fixes #58151

When a model has a null local key value, the match() method would use null
as an array offset in isset($dictionary[$key]), which:

1. Triggers a deprecation warning in PHP 8.5+
2. Incorrectly matches records with empty string foreign keys due to
   PHP's implicit null-to-empty-string conversion

This fix explicitly checks for null before accessing the dictionary,
ensuring models with null local keys don't receive any related records.

Fixes #58151
@taylorotwell taylorotwell merged commit 095ef3c into laravel:12.x Dec 22, 2025
70 checks passed
akyrey pushed a commit to akyrey/framework that referenced this pull request Dec 29, 2025
…aravel#58191)

When a model has a null local key value, the match() method would use null
as an array offset in isset($dictionary[$key]), which:

1. Triggers a deprecation warning in PHP 8.5+
2. Incorrectly matches records with empty string foreign keys due to
   PHP's implicit null-to-empty-string conversion

This fix explicitly checks for null before accessing the dictionary,
ensuring models with null local keys don't receive any related records.

Fixes laravel#58151

Co-authored-by: S. Bondarenko <s.bondarenko@mayabproject.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants