Search code examples
laravelgraphqllaravel-lighthouse

How to implement advanced validation rules in Laravel+lighthouse graphql?


Before switching to Lighthouse I used to have validation rules like this:

Rule::unique('users', 'name')->where('site_id', $this->route()->parameter('site')->id)->ignore($this->route()->parameter('user')->id),

So I need to select users with certain site_id before checking if user's name is unique. Now I have the following mutation:

updateUser(
    name: String! @rules(apply: ["App\\Rules\\UniqueUserName"])
): User! @update

But how should I provide site_id (site_id should be considered as read-only attribute) and how can I access it in my custom validation rule UniqueUserName?


Solution

  • Complex validation logic can be implemented by extending ValidationDirective class.

    Then one can write rules in the rules() method just as it was in the laravel standard request validation. Arguments are available via $this->args['site_id'].

    More info: https://lighthouse-php.com/master/security/validation.html#validate-fields