Single record with 2 fields verification - Laravel 5.1

Asked

Viewed 904 times

2

I have a table with columns id, nome, descricao and tipo. In my Request I have:

'nome' => 'required|unique:edificacoes'

So far so good, I can not register anything with the same name, but as I would not be able to register with the same name only also be the same type?

Ex: I have the record 01 | NomeTeste | Tipo1, if I try to register 02 | NomeTeste | Tipo2 I can’t. How can I make him check the name and type to block only if the 2 are equal?

Table creation:

Schema::create('edificacoes', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->longText('nome');
            $table->longText('descricao')->nullable();
            $table->char('tipo', 4);
            $table->timestamps();
});

1 answer

1


From Laravel 5.0+, you can use composite key as follows:

'nome'  => 'required|unique:{TABELA}{COLUNA}{EXCEÇÃO}{ID}

Following that specification of the documentation, I believe your case would look something like this:

'nome'  > 'required|unique:edificacoes,nome,NULL,id,tipo,$tipo'

In that rule, we are saying (in that order):

  • field name defendant;
  • field name single, to
    • table buildings
    • name field
    • any record (null)
    • primary key column is called id
    • check whether the column tipo
    • matches the value $tipo

I suggest we try to use it like this:

'nome'  > 'required|unique:edificacoes,nome,NULL,id,tipo,tipo'

In the hope that Laravel will understand that the second word tipo refers to the column tipo. But the documentation does not specify this, it simply says that the value passed there (so in my previous example I used $tipo) will be ignored.

If this way doesn’t work, it means that Laravel doesn’t have the ability to identify through the column name, causing you to have to specify the value of the $tipo manually.

  • Show! It worked by passing the $type manually. Many thanks @Marcoauréliodeleu

  • 1

    Another alternative is to install a dependency (https://github.com/felixkiss/uniquewith-validator) that adds the ability to create composite keys. But if you don’t mind passing the $tipo manually, I suggest keeping this way.

  • Blz later I’ll take a look, but in this case as I already passed the $ type even to use elsewhere, use it there "borrowed" is much faster rs

Browser other questions tagged

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