Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel request validation rules pass parameter

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.

like image 257
Sam Teng Wong Avatar asked Apr 10 '18 04:04

Sam Teng Wong


2 Answers

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'
    ];
}
like image 193
chanafdo Avatar answered Nov 08 '22 13:11

chanafdo


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,
        ]);

        // ...
    }

}
like image 43
bmatovu Avatar answered Nov 08 '22 14:11

bmatovu