Create Unique constraint with two fields in the Laravel request

Asked

Viewed 1,374 times

5

I have in the creation Migration of my table the following:

public function up()
    {
        Schema::connection('database2')->create('empresa_funcoes', function(Blueprint $table) {
            $table->increments('id');
            $table->integer('empresa_id')->unsigned();
            $table->integer('funcao_id')->unsigned();
            $table->timestamps();

            //Create a Unique Constraint
            $table->unique(['empresa_id', 'funcao_id'], 'empresa_funcao');

            //Create Foreign Keys
            $table->foreign('empresa_id')->references('id')->on('empresas')->onDelete('cascade');
            $table->foreign('funcao_id')->references('id')->on('funcoes')->onDelete('cascade');

        });
    }

In my request I need to create a restriction so I can’t register a 2x function for the same company.

I have it up to now in my Empresafuncaorequest, but I can’t just put a unique there because it will not let me register this function for another company.

public function rules()
    {
        return [
            'funcao_id' => 'required',
        ];
    }

What can I do?

I’m not asking to validate the company because it’s going on one Hidden, I don’t know if it influences.

  • you’re trying to block empresa_id and funcao_id if they are equal correct?

  • 1

    This, not to let send the X function to company Y if you already have this function in this rpesa.

1 answer

4


Create a custom validation rule, because, your case is particular, I took a look at the current rules, I think none can do what you need, maybe in parts, so make your own rule by first creating a Service Provider:

php artisan make:provider UniqueKeyDupleServiceProvider

In the folder app/Providers edit the created file: UniqueKeyDupleServiceProvider:

<?php

namespace App\Providers;

use App\Models\EmpresaFuncao;
use Illuminate\Support\ServiceProvider;


class UniqueKeyDupleServiceProvider extends ServiceProvider
{


    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 (!(EmpresaFuncao::where($attribute, $value)
                    ->where($parameters[0], $value1)
                    ->count() > 0));
            }
            return false;
        });
    }

    public function register()
    {
        //
    }
}

within that Service Provider was made an addition of custom validation and inside is the model EmpresaFuncao who does the research to find out if there is a record for a particular enterprise if the function has already been registered. If it already exists it does not let proceed and does not perform the method that is used that rule.

After creation register your providers as follows: in the archive config/app.php goes to the array of providers and add this new provider as follows:

'providers' => [
    // Other Service Providers

    App\Providers\UniqueKeyDupleServiceProvider::class,
],

In the role of request (EmpresaFuncaoRequest) add the rule created with the name of uniquekeyduple having as parameter the field funcao_id, finally being: uniquekeyduple:funcao_id, follows code example:

<?php

namespace App\Http\Requests;    
use Illuminate\Foundation\Http\FormRequest;

class EmpresaFuncaoRequest extends FormRequest
{

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'empresa_id' => 'required|uniquekeyduple:funcao_id'
        ];
    }

    public function messages()
    {
        return [
            'empresa_id.uniquekeyduple' => 'Função existente!'
        ];
    }
}

Ending in Controller

<?php

namespace App\Http\Controllers;

use App\Http\Requests\EmpresaFuncaoRequest;
use App\Http\Requests;

class EmpresaFuncaoController extends Controller
{
    public function index()
    {
        return view('empresafuncao');
    }

    public function store(EmpresaFuncaoRequest $request)
    {
        //faça as operações que assim desejar
        return $request->all();
    }
}

This is a functional example, can be further improved, but done for your specific case.

References

  • Good afternoon, and in the update how can I to it ignore itself because I have a file field I upload, and now does not let me update?

  • @Open a new database and explain what you need. OK?

  • I was able to do it, but sometimes I did too many things in the past but it worked!!

  • In my case I was making the mistake Method Illuminate\Validation\Validator::validateRequired|uniquekeyduple does not exist.. So in Request I simply changed the Rule() to 'required','uniquekeyduple:funcao_id'. (+1, excellent response)

Browser other questions tagged

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