Unique validation by ignoring softdelete items in laravel form input validation

时间:2018-03-25 18:42:50

标签: laravel laravel-validation formvalidation.io

How can I do unique validation of a given input with database record by ignoring soft delete items in Laravel? Can anyone please answer me?

2 个答案:

答案 0 :(得分:-1)

You can add a condition to the exists rule, basically filtering the results with deleted_at == NULL like this:

$request->validate([
    'foo' => 'exists:table,column,deleted_at,NULL',
]);

Taylor himself answered this question on a Github issue.

You could also create a custom validation rule:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class UniqueWithoutSoftDelete implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        // Your logic goes here
        // Return true to pass the validation
        // ie: return Model::where($attribute, $value)->exists();
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be unique.';
    }
}

To implement it in your controller add:

use App\Rules\UniqueWithoutSoftDelete;

And in your controller method:

$request->validate([
    'foo' => ['required', new UniqueWithoutSoftDelete],
]);

Hope this helps you.

答案 1 :(得分:-1)

I solved it in another way... Inside request class, write following code: public function rules() { switch ( $this->method() ){ case 'POST': return [ 'currency_id' => ['required', Rule::unique('company_currencies')->where(function ($query) { $query->where('deleted_at', Null); }) ], ]; break; }

and on top of the class file place use Illuminate\Validation\Rule;