Home > database >  Laravel unique validation - change value before checking
Laravel unique validation - change value before checking

Time:04-25

I want to check for unique url's by extracting domain name from url.

e.g. https://stackoverflow.com and https://stackoverflow.com/something?foo=bar should show error.

I have form request like below,

public function rules()
{
    return [
        'name' => 'required',
        'url' => 'required|unique:sites,url',
        'favicon' => 'nullable|image',
    ];
}

I tried changing the form request value but it's not working,

// The getDomainName() returns the stackoverflow.com for https://stackoverflow.com

$this->request->set('url', 
    Site::getDomainName($this->request->get('url'))
);

I also tried following,

$url = $this->request->get('url');

$domain = 'https://' . Site::getDomainName($url);

$uniqueRule = Rule::unique('sites', 'url')
    ->where(function ($query) use ($domain) {
        return $query->where('url', $domain) ? false : true;
    });

Any help would be appreciated, thank you!

CodePudding user response:

You need to parse url to extract domain name with protocol and then you can merge into a form request. You have to do it in starting of rules method.

$result = parse_url(request()->url);
request()->merge(['url'=>$result['scheme']."://".$result['host']]);

CodePudding user response:

Solved using prepareForValidation()

protected function prepareForValidation()
{
    $this->merge([
        'url' => 'https://' . Site::getDomainName($this->request->get('url'))
    ]);
}
  • Related