ERROR creating Unique constraint with two fields in the Laravel request?

Asked

Viewed 164 times

2

I tried to implement an example I found here at Stackoverflow however unsuccessfully.

RULE:

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

  • Another user could create the same information but only once.

CORRECT:

|ID|USER_CREATED|DESCRICAO|

|1|1|DESCARGA|

|2|2|DESCARGA|

INCORRECT:

|ID|USER_CREATED|DESCRICAO|

|1|1|DESCARGA|

|2|1|DESCARGA|

I created the Provider and changed the 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;
        });
}

Code of the structure 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',
    ];
}

My request method messages code:

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');

}

Registration in 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 he tells me that it already exists, and I haven’t registered anything in the database yet! Maybe it is a mistake in the logic of the previous, but I did not understand the operation of the previous.

inserir a descrição da imagem aqui


inserir a descrição da imagem aqui

  • That’s right, for example. I have the user Ulisses with code 1, if he registers (DESCRIPTION) DOWNLOAD (USER) 1, You can no longer register this information, but the user 2 may, only once also..

1 answer

1


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

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, then 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;
        });
}

References

Browser other questions tagged

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