Skip to content

[Laravel] required constraints on relationships are not automatically disabled for PATCH operations #7648

@ttskch

Description

@ttskch

API Platform version(s) affected: 4.2.11

Description

For example, we have the following Article and Comment models.

<?php
// app/Models/Article.php

namespace App\Models;

use ApiPlatform\Metadata\ApiResource;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

#[ApiResource(
    rules: [
        'title' => ['required', 'max:255'],
        'content' => ['required'],
    ],
)]
class Article extends Model
{
    public function comments(): HasMany
    {
        return $this->hasMany(Comment::class);
    }
}
<?php
// app/Models/Comment.php

namespace App\Models;

use ApiPlatform\Metadata\ApiResource;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

#[ApiResource(
    rules: [
        'article' => ['required'],
        'content' => ['required'],
    ],
)]
class Comment extends Model
{
    public function article(): BelongsTo
    {
        return $this->belongsTo(Article::class);
    }
}

Normally, required validation rules are automatically removed for PATCH operations.

In fact, the following API request does not result in an error:

PATCH /api/articles/1

{}

And the following API request correctly results in an error:

PATCH /api/articles/1

{
  "title": {256+ char text}
}

However, for the validation rule of the article relation field in the Comment model, required is not automatically removed for PATCH operations.

The following API request:

PATCH /api/comments/1

{}

Results in the following error:

{
  "@context": "/api/contexts/ValidationError",
  "@id": "/api/validation_errors/47cdb5bda5dce8dd",
  "@type": "ValidationError",
  "description": "The article field is required.",
  "type": "/validation_errors/47cdb5bda5dce8dd",
  "title": "Validation Error",
  "detail": "The article field is required.",
  "status": 422,
  "violations": [
    {
      "propertyPath": "article",
      "message": "The article field is required."
    }
  ]
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions