ERROR when creating unique constraint with two fields in Laravel request?

2

I tried to implement an example that I found here in StackOverflow but without success.

RULE:

  • Unique double (user_created - description) / User code you created and Description

CORRECT:

|ID|USER_CREATED|DESCRICAO|

|1|1|DESCARGA|

|2|2|DESCARGA|

INCORRECT:

|ID|USER_CREATED|DESCRICAO|

|1|1|DESCARGA|

|2|1|DESCARGA|

I created Provider and changed method boot :

public function boot()
{
    \Validator::extend('uniquekeyduple',
        function($attribute, $value, $parameters, $validator)
        {
            $value1 = (int)request()->get($parameters[0]);
            if (is_numeric($value) && is_numeric($value1))
            {
                return (!(InfoAdd::where($attribute, $value)
                        ->where($parameters[0], $value1)
                        ->count() > 0));
            }
            return false;
        });
}

Structure code of my migrate :

public function up()
{
    Schema::create('info_adds', function (Blueprint $table) {
        $table->increments('id');
        $table->string('descricao', 170);
        $table->integer('user_created')->unsigned();
        $table->foreign('user_created', 'info_add_created_user')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
        $table->integer('user_updated')->unsigned();
        $table->foreign('user_updated', 'info_add_updated_user')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
        $table->timestamps();
        $table->unique(['user_created', 'descricao'], 'user_description_infoadd');
    });
}

Code of my request method rules :

 public function rules()
 {
    return [
        'descricao' => 'required|uniquekeyduple:user_description_infoadd|max:300',
    ];
}

Code of my request method messages:

public function messages(){
    return [
        'descricao.required'=>'É necessário informar uma descrição!',
        'descricao.max'=>'Número de caracteres excedido,informe no máximo 300 caracteres!',
        'descricao.uniquekeyduple' => 'ERRO!',
        ];
}

Method Controller :

public function store(InfoAddRequest $request)
{        

    InfoAdd::create($request->all());

    Session::flash('infAddMsg', 'Informação gravada com sucesso!');

    return redirect('/infoadd/list');

}

Logging in to providers:

'providers' => 
[
    Acacha\AdminLTETemplateLaravel\Providers\AdminLTETemplateServiceProvider::class,
    Illuminate\Auth\AuthServiceProvider::class,
    Illuminate\Broadcasting\BroadcastServiceProvider::class,
    Illuminate\Bus\BusServiceProvider::class,
    Illuminate\Cache\CacheServiceProvider::class,
    Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
    Illuminate\Cookie\CookieServiceProvider::class,
    Illuminate\Database\DatabaseServiceProvider::class,
    Illuminate\Encryption\EncryptionServiceProvider::class,
    Illuminate\Filesystem\FilesystemServiceProvider::class,
    Illuminate\Foundation\Providers\FoundationServiceProvider::class,
    Illuminate\Hashing\HashServiceProvider::class,
    Illuminate\Mail\MailServiceProvider::class,
    Illuminate\Notifications\NotificationServiceProvider::class,
    Illuminate\Pagination\PaginationServiceProvider::class,
    Illuminate\Pipeline\PipelineServiceProvider::class,
    Illuminate\Queue\QueueServiceProvider::class,
    Illuminate\Redis\RedisServiceProvider::class,
    Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
    Illuminate\Session\SessionServiceProvider::class,
    Illuminate\Translation\TranslationServiceProvider::class,
    Illuminate\Validation\ValidationServiceProvider::class,
    Illuminate\View\ViewServiceProvider::class,
    App\Providers\UniqueKeyDupleServiceProvider::class,
    Laravel\Tinker\TinkerServiceProvider::class,
    App\Providers\AppServiceProvider::class,
    App\Providers\AuthServiceProvider::class,
    // App\Providers\BroadcastServiceProvider::class,
    App\Providers\EventServiceProvider::class,
    App\Providers\RouteServiceProvider::class,
    Barryvdh\DomPDF\ServiceProvider::class,

I was able to validate, but it tells me that it already exists, since I did not register anything in the database yet! maybe it is an error in the provider logic, but I did not quite understand the provider's operation.

  

  

    
asked by anonymous 01.10.2017 / 02:18

1 answer

1

The tutorial described here on the site was not observed correctly in your code is wrong as it is called validation, because in descricao has to be put user_created , see what the correct call would be: / p>

public function rules()
{
    return [
        'descricao' => 'required|uniquekeyduple:user_created|max:300',
    ];
}

The other problem encountered is because the previous tutorial checked two integers, in which case one is a string (text) and an integer, so you have to change:

public function boot()
{
    \Validator::extend('uniquekeyduple',
        function($attribute, $value, $parameters, $validator)
        {
            $value1 = (int)request()->get($parameters[0]);
            if (!empty($value) && is_numeric($value1))
            {
                return (!(InfoAdd::where($attribute, $value)
                        ->where($parameters[0], $value1)
                        ->count() > 0));
            }
            return false;
        });
}

01.10.2017 / 02:43