Edit record before passing validation rule in Laravel

Asked

Viewed 1,519 times

3

I own a form who registers clients. In the field of CPF, i format the data with jQuery by inserting the punctuation between the digits. It turns out that by inserting this formatting, my Requets do not work properly.

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 is the rule for the CPF unique:clients, it does not work, because it receives the value with the dots and the hyphenate, so when search in the bank any CPF same as the informed, never will find, because at the time of saving in the bank I withdraw these elements.

You can delete them in the validation rule itself?

  • What is the version of your Laravel?

1 answer

4


Has two viable ways to work with validation with this problem:

1) Creation of Service Provider with Validation Customizada

Create a Service Provider by command:

php composer make:provider UniqueDocumentServiceProvider

inside the briefcase app\Providers open the file UniqueDocumentServiceProvider.php and put the code right down:

<?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 that Service Provider will be made a Validator customized where you will have the option to format the information at the time of validation and thereby eliminate the problem of the other validation that takes purely the value sent by the form. When creating this file with all this information, it needs to be registered in the file app\config\app.php in the key providers as an example:

'providers' => [

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

        App\Providers\UniqueDocumentServiceProvider::class

    ],

with this record goes in the file ClientRequest.php and change unique:clients for 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 the Request (instead of the ClientRequest) , and before checking in \Validator::make remove the dots and trace 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();
}

Observing: method store is an example, emphasizing what the code would look like

So, these are the ways to do this validation that the data needs before it’s validated, to have its own format.

References:

  • Good night @Virgilio , all good ? Gave error when submitting the form , accusing that the method does not exist "Method [validateUniqueCpf] does not exist." . What can it be ?

  • I followed the steps by Serviceprovider , I believe it is more organized. As for the error, it follows the same : blob:https://web.whatsapp.com/be19ebd5-ebfc-4ad9-a29f-d690e3be0de1

  • Yes, normal registered. I don’t know if Laravel’s version influences anything, but I’m using 5.3 .

  • 1

    Edit : I reinstalled Laravel and the problem was solved. I thank @Virgilio for the full answer. Vlw !!

  • Vlw @Henriquefelix ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.