Laravel Validation Single Form Request Class for POST, PUT, PATCH


Example

Following the 'Form Request Validation' example, the same Request Class can be used for POST, PUT, PATCH so you do not have to create another class using the same/similar validations. This comes in handy if you have attributes in your table that are unique.

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules() {
    switch($this->method()) {
        case 'GET':
        case 'DELETE':
            return [];
        case 'POST':
            return [
                'name'     => 'required|max:75|unique',
                'category' => 'required',
                'price'    => 'required|between:0,1000',
            ];
        case 'PUT':
        case 'PATCH':
            return [
                'name'     => 'required|max:75|unique:product,name,' . $this->product,
                'category' => 'required',
                'price'    => 'required|between:0,1000',
            ];
        default:break;
    }
}

Starting from the top, our switch statement is going to look at the method type of the request (GET, DELETE, POST, PUT, PATCH).

Depending on the method will return the array of rules defined. If you have a field that is unique, such as the name field in the example, you need to specify a particular id for the validation to ignore.

'field_name' => 'unique:table_name,column_name,' . $idToIgnore`

If you have a primary key labeled something other than id, you will specify the primary key column as the fourth parameter.

'field_name' => 'unique:table_name,column_name,' . $idToIgnore . ',primary_key_column'

In this example, we are using PUT and passing to the route (admin/products/{product}) the value of the product id. So $this->product will be equal to the id to ignore.

Now your PUT|PATCH and POST validation rules do not need to be the same. Define your logic that fits your requirements. This technique allows you to reuse the custom messages you may have defined within the custom Form Request Class.