Laravel - Validate Unique field in update

Asked

Viewed 2,197 times

2

I have a plate field on the table that needs to be unique

IN MIGRATION

Schema::create('professors', function (Blueprint $table) {
        $table->increments('id');
        $table->boolean('inativo')->default(0);
        $table->string('matricula', 15)->unique();
        $table->string('nome', 200);
        $table->string('email', 180)->unique();
        $table->string('telefone1', 15);
        $table->string('telefone2', 15)->nullable();
        $table->string('obs', 400)->nullable();
        $table->string('file_path', 200)->nullable();
        $table->timestamps();
    });

NO REQUEST:

public function rules()
{
    return [
        'matricula' => 'required|unique:professors|max:15',
        'nome' => 'required|max:200',
        'email' => 'required|unique:professors|max:180',
        'telefone1' => 'required|max:15',
        'telefone2' => 'max:15',
        'obs' => 'max:400',
    ];
}

public function messages(){
    return [
        'matricula.required' => 'É necessário informar uma matricula para identificar o professor!',
        'matricula.max' => 'O número de matrícula excedeu a quantidade de caracteres (15) permitida!',
        'matricula.unique' => 'Ésta matrícula já está sendo utilizada por outro professor!',
        'nome.required' => 'É necessário informar um nome para o proifessor!',
        'nome.max' => 'O nome do professor excedeu a quantidade de caracteres (200) permitida!',
        'email.required' => 'É necessário informar um e-mail, que será o endereço para contato e notificações!',
        'email.max' => 'O e-mail excedeu a quantidade de caracteres (180) permitida!',
        'email.unique' => 'Éste e-mail já está sendo utilizado por outro professor!',
        'telefone1.required' => 'É necessário informar o telefone celular para contato!',
        'telefone1.max' => 'O telefone 1 excedeu a quantidade de caracteres (15) permitida!',
        'telefone2.max' => 'O telefone 2 excedeu a quantidade de caracteres (15) permitida!',
        'obs.max' => 'A observação excedeu a quantidade de caracteres (400) permitida!',
    ];
}  

CONTROLLER METHOD

public function update(ProfessorRequestUpdate $request, $id)
{
    $professor = Professor::where('id', $id)->get()->first();

    $professor->inativo = $request->inativo;

    if ($professor->matricula != $request->matricula) {
        $professor->matricula = $request->matricula;
    }

    $professor->nome = $request->nome;

    if ($professor->email != $request->email) {
        $professor->email = $request->email;
    }

    $professor->telefone1 = $request->telefone1;
    $professor->telefone2 = $request->telefone2;
    $professor->obs = $request->obs;

    if($request->hasFile('file_path') && $request->file('file_path')->isValid()) {

        if(!is_null($professor->file_path)) {
            Storage::delete('professors/' . $professor->file_path);
        }

        $professor->file_path = $request->file_path;

        $name = 'professors-'.$professor->id.'-'.kebab_case(strtolower($professor->nome));

        $extension = $request->file_path->extension();
        $nameFile = "{$name}.{$extension}";

        $professor->file_path = $nameFile;

        $upload = $request->file_path->storeAs('professors', $nameFile);

        $professor->save();

        if(!$upload)
            return redirect()
                ->route('cad/professores/lista')
                ->with(success, 'Sucesso ao carregar imagem');
    }else{
        $professor->file_path = $professor->file_path;
    }

    $professor->save();

    Session::flash('professors_Msg', 'Dados do professor atualizados com sucesso!');

    return redirect('cad/professores/lista');
}

But when I update, it does not accept that the same number be informed again, if I create another request without the Unique to pass there is error in the query, as I can proceed to accept it inform or skip this field if it is the same value?

1 answer

5


You can force Laravel to ignore one ID during the single field check, in this case just pass the teacher id as the third parameter.

'matricula' => 'required|unique:professors,matricula,' . $request->id . '|max:15',

More information

  • My validation rules I put right into controller, but I think it gives way that it’s now supposed to work, taking the id of $request, you can also pass the id as a parameter for public function rules($id), I have no way to test it now, but tonight I confirm it and update the answer if necessary.

  • How will he recognize this $request->id variable?

  • All right, thank you..

  • I need to be able to pass the id value to Request in the Rules() method that will work.. I tested it that way and it worked! 'matricula' => 'required|Unique:professors,matricula,2|max:15', this number two and the teacher id field, the matricula field is another field that has 14 characters.

  • How do I validate within the controller without creating a Request file for validation? sometimes that way I can solve this problem

  • Here is an example of the way I did: https://www.rfmeier.net/creating-custom-form-request-laravel/, he explains how to create a Request custom, which is what you did, but I think the best in your case would be able to pass the parameter, just try to put $this->id in his function rules() for testing

  • I’m going to do some more tests, but it seems I had forgotten to put an <input type="Hidden" name="id" value="{$professor->id}}"/> in the form, now there inside the Rules I got the id and it seems that the validation worked!

  • Really the problem has been solved, thank you very much for your help!!

  • I’m glad I could help.

Show 4 more comments

Browser other questions tagged

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