Cześć,
Męczę się z tym już trochę i nie wiem jak to można ugryźć. Będę niezmiernie wdzięczny jak ktoś mi pokaże jak do tego podejść.
Korzystam z GraphQL (Lighthouse) na Laravelu i mam taką mutację:
addBook(
title: String! @rules(apply: ["required", "string", "min:3", "max:20"])
year_of_writing: Int! @rules(apply: ["required", "numeric"])
author_id: Int! @rules(apply: ["required", "numeric", "exists:authors,id"])
): Book @BookValidation @create
Stworzyłem sobie do niej dyrektywę, bo muszę sprawdzić czy rok urodzenia autora jest 10 lat mniejszy od roku napisania książki.
namespace App\GraphQL\Directives;
use Illuminate\Validation\Rule;
use Nuwave\Lighthouse\Schema\Directives\ValidationDirective;
class BookValidationDirective extends ValidationDirective
{
/**
* Name of the directive.
*
* @return string
*/
public function name(): string
{
return 'BookValidation';
}
/**
* @return mixed[]
*/
public function rules(): array
{
return [
'year_of_writing' => ['required'],
'author_id' => ['required'],
];
}
}
I tu się zatrzymałem. Próbowałem stworzyć klasę z regułą ale tu chyba nie można przekazywać wielu parametrów. Próbowałem też jako jeden z tablicą, ale też nic.
W rules dopisywałem:
'author_id' => ['required', new CheckYear (<<próbowałem tu wcisnąć dwie wartości na różne sposoby, ale nie udało mi się>>)],
A tak wyglądał pliczek:
<?php
namespace App\GraphQL\Directives;
use Illuminate\Contracts\Validation\Rule;
class CheckYear implements Rule
{
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
//return <<Tutaj miał być kod w stylu $value['year_of_writing''] > $value['author_year_of_birth'] + 10>>;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The validation error message.';
}
}
Więc nakieruje mnie ktoś lub da przykład jak dokonać walidacji, czy rok napisania książki jest większy o conajmniej 10 lat od roku urodzenia autora(z bazy wcześniej trzeba jeszcze pobrać ten rok urodzenia)