Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ public function create(string $resourceClass, string $property, array $options =
$type = Type::object($relation['related']);
if ($collection) {
$type = Type::iterable($type);
} elseif (true === ($relation['nullable'] ?? false)) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that this changes the output for every existing nullable BelongsTo: JSON Schema/OpenAPI become nullable and GraphQL drops the ! on these fields (inputs included). It's the right fix and it matches what Doctrine does but we need to mention this in the changelog.

$type = Type::nullable($type);
}

return $propertyMetadata
Expand Down
11 changes: 11 additions & 0 deletions src/Laravel/Eloquent/Metadata/ModelMetadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ public function getRelations(Model $model): array
}

$relations = [];
$nullableColumns = null;
$class = new \ReflectionClass($model);

foreach ($class->getMethods() as $method) {
Expand Down Expand Up @@ -262,6 +263,16 @@ public function getRelations(Model $model): array
'related' => \get_class($relation->getRelated()),
'foreign_key' => method_exists($relation, 'getForeignKeyName') ? $relation->getForeignKeyName() : null,
];

if ($relation instanceof BelongsTo) {
$nullableColumns ??= array_column($model->getConnection()->getSchemaBuilder()->getColumns($model->getTable()), 'nullable', 'name');
$relations[$relationName]['nullable'] = (bool) ($nullableColumns[$relation->getForeignKeyName()] ?? false);
}
}

// Don't cache nullability read from a missing table, see getAttributes().
if ([] === $nullableColumns) {
return $relations;
}

return $this->relations[$model::class] = $relations;
Expand Down
12 changes: 12 additions & 0 deletions src/Laravel/Eloquent/State/PersistProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,18 @@ public function process(mixed $data, Operation $operation, array $uriVariables =
$toMany = [];

foreach ($this->modelMetadata->getRelations($data) as $relation) {
// isset() is false for null, so an explicit null would be skipped and saved as a column named after the relation.
if (
(BelongsTo::class === $relation['type'] || MorphTo::class === $relation['type'])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the MorphTo branch isn't covered, dissociate() also nulls the type column there. Could you add a test for it?

&& \array_key_exists($relation['name'], $data->getAttributes())
&& null === $data->getAttributes()[$relation['name']]
) {
$data->{$relation['method_name']}()->dissociate();
unset($data->{$relation['name']});

continue;
}

if (!isset($data->{$relation['name']})) {
continue;
}
Expand Down
81 changes: 81 additions & 0 deletions src/Laravel/Tests/NullableBelongsToTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Laravel\Tests;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Orchestra\Testbench\Concerns\WithWorkbench;
use Orchestra\Testbench\TestCase;
use Workbench\App\Models\DeliveryRequest;
use Workbench\Database\Factories\TimeSlotFactory;

/**
* @see https://github.com/api-platform/core/issues/8664
*/
final class NullableBelongsToTest extends TestCase
{
use RefreshDatabase;
use WithWorkbench;

public function testPostWithExplicitNullBelongsTo(): void
{
$response = $this->postJson('/api/delivery_requests', [
'pickupTimeSlot' => null,
'note' => 'no slot',
], ['accept' => 'application/ld+json', 'content-type' => 'application/ld+json']);

$response->assertStatus(201);
$this->assertNull(DeliveryRequest::query()->sole()->pickup_time_slot_id); // @phpstan-ignore-line
}

public function testPatchWithExplicitNullClearsBelongsTo(): void
{
$iri = $this->createDeliveryRequestWithSlot();

$response = $this->patchJson($iri, [
'pickupTimeSlot' => null,
], ['accept' => 'application/ld+json', 'content-type' => 'application/merge-patch+json']);

$response->assertStatus(200);
$this->assertNull(DeliveryRequest::query()->sole()->pickup_time_slot_id); // @phpstan-ignore-line
}

public function testOmittingBelongsToKeepsIt(): void
{
$iri = $this->createDeliveryRequestWithSlot();
$slotId = DeliveryRequest::query()->sole()->pickup_time_slot_id; // @phpstan-ignore-line

$response = $this->patchJson($iri, [
'note' => 'updated',
], ['accept' => 'application/ld+json', 'content-type' => 'application/merge-patch+json']);

$response->assertStatus(200);
$deliveryRequest = DeliveryRequest::query()->sole();
$this->assertSame($slotId, $deliveryRequest->pickup_time_slot_id); // @phpstan-ignore-line
$this->assertSame('updated', $deliveryRequest->note); // @phpstan-ignore-line
}

private function createDeliveryRequestWithSlot(): string
{
$slot = TimeSlotFactory::new()->create();

$response = $this->postJson('/api/delivery_requests', [
'pickupTimeSlot' => '/api/time_slots/'.$slot->id, // @phpstan-ignore-line
'note' => 'with slot',
], ['accept' => 'application/ld+json', 'content-type' => 'application/ld+json']);
$response->assertStatus(201);
$this->assertNotNull(DeliveryRequest::query()->sole()->pickup_time_slot_id); // @phpstan-ignore-line

return $response->json('@id');
}
}
13 changes: 13 additions & 0 deletions src/Laravel/workbench/app/Models/DeliveryRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
Expand All @@ -35,6 +36,18 @@
],
]
),
new Patch(
normalizationContext: [
'groups' => [
'delivery_request:read',
],
],
denormalizationContext: [
'groups' => [
'delivery_request:write',
],
]
),
]
)]
#[ApiProperty(property: 'pickupTimeSlot', serialize: new Groups(['delivery_request:read', 'delivery_request:write']))]
Expand Down
Loading