Create a custom validation with the command line:
php artisan make:rule CategoryInputUnique
generating in the folder app\rules
a class CategoryInputUnique
, inside has a method with the following signature passes($attribute, $value)
where to write a code to search the database if there is a repetition of that name with that category number (it is worth remembering that it is good to create an index in these two fields by the database), example:
<?php namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\DB;
class CategoryInputUnique implements Rule
{
public function __construct()
{
//
}
public function passes($attribute, $value)
{
$categoria = request('categoria', 0);
$id = (int)request('id', 0);
$result = DB::table('insumos')
->where('insumo', '=', $value)
->where('categoria', '=', $categoria);
if ($id === 0) {
return $result->count() === 0;
}
$model = $result->first();
if ($model) {
return (int)$model->id === $id;
}
return true;
}
public function message()
{
return 'The validation error message.';
}
}
in this code will verify if there is repetition, where was informed randomly table name (put the real name of your table) and the two fields category and input (put here also according to your table) and will count if there are records with these two information.
To use only declare in array
validation to your instance:
public function rules()
{
return [
'preco' => 'required',
'categoria' => 'required',
'insumo' => ['required',
'min:3',
'max:100',
function ($attribute, $value, $fail) {
$categoria = request('categoria', 0);
$id = (int)request('id', 0);
$result = DB::table('insumos')
->where('insumo', '=', $value)
->where('categoria', '=', $categoria);
if ($id === 0) {
if (!($result->count() === 0)){
$fail($attribute.' is invalid.');
}
}
$model = $result->first();
if ($model) {
if (!((int)$model->id === $id)) {
$fail($attribute.' is invalid.');
}
}
return true;
}
],
];
}
You can use the method facade
to create an extension within the class AppServiceProvider
:
public function boot()
{
Validator::extend('categoriainputunique', function (
$attribute,
$value,
$parameters,
$validator
) {
$categoria = request('categoria', 0);
$id = (int)request('id', 0);
$result = DB::table('insumos')
->where('insumo', '=', $value)
->where('categoria', '=', $categoria);
if ($id === 0) {
return $result->count() === 0;
}
$model = $result->first();
if ($model) {
return (int)$model->id === $id;
}
return true;
});
}
and in the validation call only by extension name:
public function rules()
{
return [
'preco' => 'required',
'categoria' => 'required',
'insumo' => ['required', 'min:3','max:100', 'categoriainputunique'],
];
}
References
running 100% vlw Master! you are a monster!
– MichaelCosta