Search code examples
phplaravellaravel-routinglaravel-validation

How to write validation rule with resource in Laravel?


I use Laravel 8 with Resource to define routes in api.php and DestroyProductRequest in my controller:

Route::resources([
    'product' => ProductController::class,
]);

In the controller:

public function destroy(DestroyProductRequest $request, Product $product) {
    $product->delete();

    return Response::HTTP_OK;
}

In the DestroyProductRequest.php:

public function rules() {
    return [
        'id' => 'required|integer|exists:products,id',
    ];
}

Now the key is the Route::resource convert the incoming id from the url into a model. But now how can I write the correct rule in the the rules() function?

Now it sais id: ["The id field is required."] in the error response.

Any idea?


Solution

  • By default Laravel does not validate the route parameters. You have add custom logic in order to work

    public function rules()
    {
        return [
            'product' => 'required|integer|exists:products,id',
        ];
    }
    
    protected function validationData()
    {
        // Add the Route parameters to you data under validation
        return array_merge($this->all(),$this->route()->parameters());
    }
    

    In a normal use case, you wouldn't validate route request. Laravel would return a 404 Not Found exception. Which is a standard and appropriate response.