Custom validation on form request Laravel

63 Views Asked by At

I want make a validation for my products table where SKU field deleted_at is not null (yes i have softdeletes).

what i have done is make Custom Rules:

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)
    {
        // Check if the SKU exists and its deleted_at field is not null
        return \DB::table('products')
            ->where('sku', $value)
            ->whereNotNull('deleted_at')
            ->exists();
    }

    public function message()
    {
        return 'The SKU is invalid or has not been deleted.';
    }
}

and this is my Product 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('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' => ['required', new SkuDeletedValidationRule], 'unique:products,sku,' . $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'
        ];
    }

    protected function prepareForValidation()
    {
        $this->merge([
            'slug' => $this->setSlug($this->name),
            'is_publish' => $this->is_publish == 'on' ?? false
        ]);
    }

    private function setSlug($name)
    {
        $slug = Str::slug($name);
        $originalSlug = $slug;
        $i = 1;
        while (Product::whereSlug($slug)->exists()) {
            $slug = $originalSlug . '-' . $i++;
        }

        return $slug;
    }
}

my problem is, i put the custom rules but it passes the validation. what i wanted to do is if the SKU column values exists and deleted_at is not null return the messages

this sku has been created, please restore the deleted data

0

There are 0 best solutions below