Skip to content

Commit

Permalink
fix: HasAttributes::relationsToArray isset logic
Browse files Browse the repository at this point in the history
  • Loading branch information
calebdw committed Jul 24, 2024
1 parent 7c5c83e commit 3e55014
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,8 @@ public function relationsToArray()
// If the relation value has been set, we will set it on this attributes
// list for returning. If it was not arrayable or null, we'll not set
// the value on the array because it is some type of invalid value.
if (isset($relation)) {
if (isset($relation) || is_null($value)) {
/** @phpstan-ignore variable.undefined ($relation is defined, but `isset` returns false when `null`) */
$attributes[$key] = $relation;
}

Expand Down
20 changes: 20 additions & 0 deletions tests/Database/DatabaseConcernsHasAttributesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Concerns\HasAttributes;
use Illuminate\Support\Collection;
use Mockery as m;
use PHPUnit\Framework\TestCase;

class DatabaseConcernsHasAttributesTest extends TestCase
Expand All @@ -21,6 +23,24 @@ public function testWithConstructorArguments()
$attributes = $instance->getMutatedAttributes();
$this->assertEquals(['some_attribute'], $attributes);
}

public function testRelationsToArray()
{
$mock = m::mock(HasAttributesWithoutConstructor::class)
->makePartial()
->shouldAllowMockingProtectedMethods()
->shouldReceive('getArrayableRelations')->andReturn([
'arrayable_relation' => Collection::make(['foo' => 'bar']),
'invalid_relation' => 'invalid',
'null_relation' => null,
])
->getMock();

$this->assertEquals([
'arrayable_relation' => ['foo' => 'bar'],
'null_relation' => null,
], $mock->relationsToArray());
}
}

class HasAttributesWithoutConstructor
Expand Down

0 comments on commit 3e55014

Please sign in to comment.