Exception in Laravel Request validation

Asked

Viewed 73 times

1

I have a Request that validates the data. One of the validations is the unique to restrict the repetition of items. However, items are entered in categories. I need that when the item is of another category, he let the register.

public function rules()
{
    return [
        'preco'         => 'required',
        'categoria'     => 'required',
        'insumo'        => 'required|min:3|max:100|unique:insumos,insumo,'.$this->id,
    ];
}

'input' this is the amount that need to release the duplication, if the category you are receiving in the form is different from the one already registered in the bank.

for example:

Id - Insumo - Categoria - Preço
1  - Tomate -    5      - 1.00

if you register another "Tomato", but the category is another value, let it register.

Can anyone imagine a way to do that ?

Thus staying in the database:

Id - Insumo - Categoria - Preço
1  - Tomate -    5      - 1.00
2  - Tomate -    7      - 1.50

1 answer

2


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

  • 1

    running 100% vlw Master! you are a monster!

Browser other questions tagged

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