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
you’re trying to block
empresa_id
andfuncao_id
if they are equal correct?– novic
This, not to let send the X function to company Y if you already have this function in this rpesa.
– Raylan Soares