Search code examples
laravelformsvalidationrequestlaravel-validation

Laravel unique validation must include appended text when validating


I am using the Laravel tenancy package in which there is a domains table in my database and each value in the domain column within this table is appended with .test.co.uk.

enter image description here

When the user enters the URL in the form, they are presented with an input element (shown above) in which they enter a URL/Domain but the .test.co.uk is already appended so the only thing they need to enter is the text that goes before that, e.g. they would enter johnsmith and in the domain column it would store johnsmith.test.co.uk. The problem I have is that I need the validation on this column to be unique but also include the .test.co.uk when performing the validation so that it looks at the value stored in the table because if a user enters johnsmith and there is currently a record in the domains table where the value is johnsmith.test.co.uk then the validation would pass but I need the validation to fail in this scenario. I am currently using a Request class which is extending the FormRequest class and have this:

public function rules()
{
   return [
       'url' => 'required|string|unique:domains,domain',
   ];
}

I have also tried a rule object but I don't think a rule object is the correct solution to this problem. Is there a convenient "Laravel" way of doing this?


Solution

  • In your Request class use prepareForValidation()

    Docs: https://laravel.com/docs/7.x/validation#prepare-input-for-validation

    protected function prepareForValidation()
    {
        $this->merge([
            'url' => $this->url . '.test.co.uk',
        ]);
    }