Laravel 5 unique validation rule with mutated attributes

Lost in space
May 13 · 1 min read

I love Laravel, it’s powerfull, effective and elegant, but today I’ve been disapointed on this specific topic, let me explain.

Duplicate entry not handled by the validator, and BOOM !

In order to improve the readability of a field called “siret” I used a getter in my model which insert spaces inside a string, nothing extraordinary, but the problem comes when you decide to apply a unique constraint on the FormRequest you’ve created.

The unique rule is bypassed and you’re dealing with a superb QueryException ! What could you do ?! Transforming your request in the controller before the call to update/store method obviously ?!

I’ve tried so many times, it turns me mad before I dived into the FormRequest class and found this :

/**
* Get data to be validated from the request.
*
*
@return array
*/
protected function validationData()
{
return $this->all();
}

Bingo !

Now in order to remove spaces in my input I just had to override the validationData function in my custom FormRequest class like this :

class EtablissementRequest extends FormRequest
{

protected function validationData()
{
$input = parent::validationData();

if (isset($input['siret'])) {
$input['siret'] = str_replace(' ','',$input['siret']);
}

return $input;
}
...
}

I hope this trick will help someone saving time on Laravel 5.8. Bye !

A little part of me : dev, space, politics, motorcycle

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade