I'm going straight to the point here, I am wondering if it is possible to pass a parameter on a validation rule
in Laravel.
Here's my code:
I need to pass the $product->id
to the ProductUpdateRequest
class.
I've read some articles and to no avail can't pass a parameter into it. my other solution was to not use the validation rule class and do the validation directly on the controller by using $request->validate[()]
. Since I can access the $product->id
on the controller I can easily do the validation. but out of curiosity is there a way for me to pass the $product->id
on the validation class
?
CONTROLLER
public function update(ProductUpdateRequest $request, Product $product)
{
$request['detail'] = $request->description;
unset($request['description']);
$product->update($request->all());
return response([
'data' => new ProductResource($product)
], Response::HTTP_CREATED);
}
VALIDATION RULE
public function rules()
{
return [
'name' => 'required|max:255|unique:products,name'.$product->id,
'description' => 'required',
'price' => 'required|numeric|max:500',
'stock' => 'required|max:6',
'discount' => 'required:max:2'
];
}
Any suggestions/answers/help would be highly appreciated.
You can get the resolved binding from request
$product = $this->route('product');
Inside your rules
method you can get the product instance with the above method.
public function rules()
{
$product = $this->route('product');
return [
'name' => 'required|max:255|unique:products,name'.$product->id,
'description' => 'required',
'price' => 'required|numeric|max:500',
'stock' => 'required|max:6',
'discount' => 'required:max:2'
];
}
This is how I would validate unique product name on update. I pass the product ID as a route parameter, the use the unique
validation rule to validate that it the product name does't exist in the Database except for this product (id).
class ProductController extends Controller {
public function update(Request $request, $id) {
$this->validate($request, [
'name' => 'required|max:255|unique:products,name'.$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