Repository navigation
How to organize array elements through attributes in laravel data ? #1150
|
Example: class StoreDTO extends Data
{
/**
* @param array<int, int> $messagesId
* @param array<int, int> $chatsId
*/
public function __construct(
#[Sometimes, ArrayType]
public ?MessageStoreDTO $message,
#[ArrayType, Exists('messages', 'id'), Max(10)]
public array $messagesId,
#[ArrayType, Exists('chats', 'id'), Max(10)]
public array $chatsId,
) {
}
/** @return array<string, mixed> */
public static function rules(): array
{
return [
'messagesId.*' => ['distinct:strict', 'int'],
'chatsId.*' => ['distinct:strict', 'int'],
];
}
}
|
Replies: 1 comment
|
Validation attributes attached to an The intended solution is to keep collection-level constraints as attributes and define element constraints in use Spatie\LaravelData\Attributes\Validation\ArrayType;
use Spatie\LaravelData\Attributes\Validation\Distinct;
use Spatie\LaravelData\Attributes\Validation\Exists;
use Spatie\LaravelData\Attributes\Validation\IntegerType;
use Spatie\LaravelData\Attributes\Validation\Max;
use Spatie\LaravelData\Attributes\Validation\Sometimes;
class StoreDTO extends Data
{
public function __construct(
#[Sometimes, ArrayType, Max(10)]
public array $messagesId,
#[ArrayType, Max(10)]
public array $chatsId,
) {}
public static function rules(): array
{
return [
'messagesId.*' => [
new IntegerType(),
new Distinct(Distinct::Strict),
new Exists('messages', 'id'),
],
'chatsId.*' => [
new IntegerType(),
new Distinct(Distinct::Strict),
new Exists('chats', 'id'),
],
];
}
}Laravel Data explicitly supports using its validation-attribute objects inside This also gives precise errors such as If this answers the per-element attribute question, please mark it as the answer so the wildcard pattern is easy to find. |
Validation attributes attached to an
arrayproperty target the property path itself (messagesId), not its wildcard element path (messagesId.*). There is currently no property-attribute syntax that redirectsIntegerType,Distinct, orExiststo every scalar item.The intended solution is to keep collection-level constraints as attributes and define element constraints in
rules():