Edit record before passing by validation rule in Laravel

2

I have a form that registers clients. In the CPF registry field, I format the data with jQuery by entering the punctuation between the digits. It turns out that by entering this formatting, my Requets rules do not work correctly.

ClientRequest.php

public function rules()
{    
    return [

            'user_create_id' => 'required|integer',
            'marital_status_id' => 'required|integer',
            'people_type' => 'required',
            'name' => 'required|max:100|min:10',
            'cpf' => 'required|max:14|min:14|unique:clients',
            'rg' => 'max:13|min:6',
            'data_nasc' => 'required',
            'phone' => 'required|min:10|max:15',
            'email' => 'min:10|max:225|email',
            'has_credit_card' => 'required',
            'has_current_account' => 'required',
    ];
}

Where the rule for the CPF unique:clients , it does not work because it receives the value with the points and the hyphen >, so when you search the bank for some CPF equal to the one informed, you will never find it, because at the moment of saving in the bank I take those elements.

Can you delete them in the validation rule itself ?

    
asked by anonymous 25.11.2016 / 21:20

1 answer

3

It has two viable ways to work with validation with this problem:

1) Creating Service Provider with Custom Validation

Create a Service Provider by the command:

  

php composer make:provider UniqueDocumentServiceProvider

In the app\Providers folder open the file UniqueDocumentServiceProvider.php and place the code just below it:

<?php namespace App\Providers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;

class UniqueDocumentServiceProvider extends ServiceProvider
{
    public function boot()
    {
        //Criação de uma nova validação  
        \Validator::extend('unique_cpf', function ($attribute, 
                                                   $value, 
                                                   $parameters, 
                                                   $validator) {

            $value = str_replace(['.','-'],'', $value);
            return ((DB::table('clients')
                       ->where('cpf','=', $value)
                       ->count()) == 0 );

        });

        //Mensagem da validação customizada
        \Validator::replacer('unique_cpf', function ($message, 
                                                     $attribute, 
                                                     $rule, 
                                                     $parameters) {

            return 'CPF existente';

        });
    }    
    public function register()
    {
    }
}

in this Service Provider will be done Validator where you have the option of formatting the information at the time of validation and thus eliminating the problem of the other validation that takes the value sent by the form purely. When creating this file with all this information, it needs to be registered in the app\config\app.php file in the providers key as an example:

'providers' => [

        /*
         * Laravel Framework Service Providers...
         */
        .....

        App\Providers\UniqueDocumentServiceProvider::class

    ],

With this record it goes in the file ClientRequest.php and change unique:clients by unique_cpf :

public function rules()
{    
    return [

            'user_create_id' => 'required|integer',
            'marital_status_id' => 'required|integer',
            'people_type' => 'required',
            'name' => 'required|max:100|min:10',
            'cpf' => 'required|max:14|min:14|unique_cpf',
            'rg' => 'max:13|min:6',
            'data_nasc' => 'required',
            'phone' => 'required|min:10|max:15',
            'email' => 'min:10|max:225|email',
            'has_credit_card' => 'required',
            'has_current_account' => 'required',
    ];
}

With these modifications will have the expected effect.

2) Doing the manual process directly in the Controller

Use Request (instead of ClientRequest ), and before checking on \ Validator :: make remove the dots and dash from your cpf :

public function store(Request $request)
{
    $rules = [
      'name' => 'required|max:100|min:10',
      'cpf' => 'required|max:14|unique:pessoas'
    ];

    $value = $request->except('cpf');

    //removendo pontos e traço e criando a chave para validação.
    $value['cpf'] = str_replace(['.','-'], '', $request->input('cpf'));

    //Validação ...
    $validator = \Validator::make($value, $rules);

    //Se falhar retorne com os erros !!!
    if ($validator->fails())
    {
        return redirect('pessoa')
            ->withErrors($validator)
            ->withInput();
    }

    //Se passar desse if os dados são válido faça aqui as outras operações
    return $request->all();
}

Note: method store is an example, emphasizing how the code

So these are the ways to do this validation that the data needs before being validated, have a format of its own.

References:

26.11.2016 / 00:29