Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Chron's avatar

How to validate existence and ownership of a data?

I don't know if this is recommended or there is a cleaner way to do it but I have a custom rule that checks the ownership. Is this fine?

//OwnsToy.php

namespace App\Rules;

use App\Models\Child;

//..

private $child;

public function __construct(Child $child)
{
	$this->child = $child;
}

public function validate(string $attribute, mixed $value, Closure $fail): void
{
	$toy = $this->child->toy->firstWhere('name', $value);
	if(!$toy) {
		$fail('Toy not found.');
	}
}

Then I have this in FormRequest

'toy.*.name' => ['exists:toy,name', new OwnsToy($this->route('child'))],
0 likes
2 replies
Snapey's avatar

sounds very loose relationship. I assume somewhere you check for, and prevent duplicate toy names?

Chron's avatar

No no, duplicate toy names are fine. I just want to check if the toy owns by the child.

Please or to participate in this conversation.