I create laravel form validation request and have unique rules on that validation.
I want use it on store
and update
method without create new form request validation again.
but the problem is when on store
the id doesnt exist and the validate is passed
and when on update
i failed the pass the validating because the id is exist on storage
i want to ignore the id on unique
rules but use same form validate request
what is best practice to check on form validate request class if this action from store or update method to ignore unique id ?
you can also follow basic tutorial from scratch here: Laravel Form Validation Example. Basically, you can create your own request class using bellow command: Now you can see bellow solution one by one and you can use anyone that you require for unique validation. * Determine if the user is authorized to make this request.
Now, let's make the email as unique under form request in laravel 8. Step 2: go to your controller and use this StudentFormRequest in store and update function as follows: * Determine if the user is authorized to make this request. * Get the validation rules that apply to the request. Thanks for reading.
Each form request generated by Laravel has two methods: authorize and rules. As you might have guessed, the authorize method is responsible for determining if the currently authenticated user can perform the action represented by the request, while the rules method returns the validation rules that should apply to the request's data:
After validating incoming request data using a form request or a manually created validator instance, you may wish to retrieve the incoming request data that actually underwent validation. This can be accomplished in several ways. First, you may call the validated method on a form request or validator instance.
Ok.. i can do it like @porloscerros Ψ suggest
public function rules()
{
$rules = [
'name' => 'required|string|unique:products|max:255',
];
if (in_array($this->method(), ['PUT', 'PATCH'])) {
$product = $this->route()->parameter('product');
$rules['name'] = [
'required',
'string',
'max:255',
Rule::unique('loan_products')->ignore($product),
];
}
return $rules;
}
Try this, it worked for me.
Laravel unique: third param can exclude the id for example, of the record, like this:
public function rules()
{
return [
'name' => 'required|string|max:255|unique:products,'.$this->id,
];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With