自定义验证始终在表单请求中返回 true Laravel

huangapple go评论96阅读模式
英文:

Custom validation always return true on form request laravel

问题

我有一个自定义验证用于我的表单请求。当用户输入值并且该值存在且字段 deleted_at 不为 null 时,此验证应该起作用。

问题是,即使我输入了不存在的值并且 deleted_at 为 null,验证仍然起作用。

这是我所做的:

customValidation:

<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\Rule;
use App\Models\Product;

class SkuDeletedValidationRule implements Rule
{
    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function passes($attribute, $value)
    {
        // Retrieve the模型 instance based on the SKU value
        $model = Product::where('sku', $value)->first();

        // Check if the模型 exists and其 deleted_at 不为 null
        if ($model && $model->deleted_at !== null) {
            return true;
        }
        return false;
    }

    public function message()
    {
        return '该 :attribute 已存在但已被删除,请恢复它。';
    }
}

我的表单请求:

use App\Models\Product;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Str;
use App\Rules\SkuDeletedValidationRule;

class ProductRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return auth('cms-admin')->check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array|string>
     */
    public function rules(): array
    {
        return [
            'name' => 'required',
            'sku' => [new SkuDeletedValidationRule, 'required' . $this->product->id],
            'sku_merchant' => 'nullable|unique:products,sku_merchant,' . $this->product->id,
            'slug' => 'nullable',
            'is_publish' => 'required',
            'price' => 'required',
            'description' => 'required',
            'discount' => 'nullable',
            'images.*' => 'required',
            'category.*' => 'nullable|exists:categories,id',
            'supplier_id' => 'required',
            'buyer_price' => 'required',
        ];
    }
}

我的控制器:

public function store(ProductRequest $request)
{
    $this->productService->create($request->validated());

    return redirect(route('admin.product.index'))->with('success', '产品已创建!');
}

当我输入不存在的值时,请修复我的自定义验证以使其正常工作。非常感谢!

英文:

I have custom validation for my form request. When users input the value and the value exists also field deleted_at is not null this validation should be working.

the problem is even when I input the value that is not exists and deleted_at is null. the validation still working.

this is what i have done

customValidation:

&lt;?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\Rule;
use App\Models\Product;

class SkuDeletedValidationRule implements Rule
{
    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function passes($attribute, $value)
    {
        // Retrieve the model instance based on the SKU value
        $model = Product::where(&#39;sku&#39;, $value)-&gt;first();

        // Check if the model exists and its deleted_at is not null
        if( $model &amp;&amp; $model-&gt;deleted_at !== null){
            return true;
        }
        return false;
    }

    public function message()
    {
        return &#39;The :attribute is exists but has been deleted, please restore it.&#39;;
    }
}

my form request:

use App\Models\Product;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Str;
use App\Rules\SkuDeletedValidationRule;


class ProductRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return auth(&#39;cms-admin&#39;)-&gt;check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array&lt;string, \Illuminate\Contracts\Validation\ValidationRule|array|string&gt;
     */
    public function rules(): array
    {
        return [
            &#39;name&#39; =&gt; &#39;required&#39;,
            &#39;sku&#39; =&gt; [new SkuDeletedValidationRule, &#39;required&#39; . $this-&gt;product?-&gt;id],
            &#39;sku_merchant&#39; =&gt; &#39;nullable|unique:products,sku_merchant,&#39; . $this-&gt;product?-&gt;id,
            &#39;slug&#39; =&gt; &#39;nullable&#39;,
            &#39;is_publish&#39; =&gt; &#39;required&#39;,
            &#39;price&#39; =&gt; &#39;required&#39;,
            &#39;description&#39; =&gt; &#39;required&#39;,
            &#39;discount&#39; =&gt; &#39;nullable&#39;,
            &#39;images.*&#39; =&gt; &#39;required&#39;,
            &#39;category.*&#39; =&gt; &#39;nullable|exists:categories,id&#39;,
            &#39;supplier_id&#39; =&gt; &#39;required&#39;,
            &#39;buyer_price&#39; =&gt; &#39;required&#39;
        ];
    }
}

my Controller:

    public function store(ProductRequest $request)
    {
        $this-&gt;productService-&gt;create($request-&gt;validated());

        return redirect(route(&#39;admin.product.index&#39;))-&gt;with(&#39;success&#39;, &#39;product created!&#39;);
    }

when i input the non existing value

> 自定义验证始终在表单请求中返回 true Laravel

what to fix in my custom validation to be this working well? thank you in advanced.

答案1

得分: 1

要检索已经软删除的数据,您需要使用withTrashed()方法。

只需修改以下行:

$model = Product::where('sku', $value)->first();

$model = Product::withTrashed()->where('sku', $value)->first();

根据您的验证消息,我假设当您找到已经软删除的具有相同SKU的数据时,应该返回false。

/**
 * 运行验证规则。
 *
 * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
 */
public function passes($attribute, $value)
{
    // 基于SKU值检索模型实例
    $model = Product::withTrashed()->where('sku', $value)->first();

    // 检查模型是否存在且其deleted_at不为null
    if ($model && $model->deleted_at !== null) {
        return false;
    }
    return true;
}
英文:

To retrieve data that has been softly deleted, you need to use withTrashed() method.

Simply modify the following line:

$model = Product::where(&#39;sku&#39;, $value)-&gt;first();

To

$model = Product::withTrashed()-&gt;where(&#39;sku&#39;, $value)-&gt;first();

And based on your verification message, I assume you should return false when you find data with the same SKU that has been softly deleted.

/**
 * Run the validation rule.
 *
 * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
 */
public function passes($attribute, $value)
{
    // Retrieve the model instance based on the SKU value
    $model = Product::withTrashed()-&gt;where(&#39;sku&#39;, $value)-&gt;first();

    // Check if the model exists and its deleted_at is not null
    if( $model &amp;&amp; $model-&gt;deleted_at !== null){
        return false;
    }
    return true;
}

答案2

得分: 0

我认为你正在使用SoftDelete特性和架构。

如果你已经删除了它,你不能添加新的sku,你有两个选项。

如果之前删除过,请尝试这个:

Product::withTrashed()->where('sku', $value)->restore();

或者你可以在插入新的之前强制删除它:

Product::where('sku', $value)->forceDelete();
英文:

I think you are using SoftDelete traits and schema.

You can't add new sku if you have already deleted it you have two options.

Try this if previously deleted.

Product::withTrashed()-&gt;where(&#39;sku&#39;, $value)-&gt;restore();

Or you can force delete it before inserting new

Product::where(&#39;sku&#39;, $value)-&gt;forceDelete();

huangapple
  • 本文由 发表于 2023年8月10日 11:25:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76872471.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定