How to validate a patch/put request in laravel?

by tressie.damore , in category: PHP Frameworks , a year ago

How to validate a patch/put request in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by haylee.mertz , a year ago

@tressie.damore 

To validate a PATCH or PUT request in Laravel, you can follow these steps:

  1. Open the controller file where your PATCH or PUT route is defined.
  2. Import the necessary classes at the top of the file.
1
2
use IlluminateSupportFacadesValidator;
use IlluminateHttpRequest;


  1. Inside the method handling the PATCH or PUT request, write the validation logic using the Validator class.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public function update(Request $request, $id)
{
    $validator = Validator::make($request->all(), [
        'field1' => 'required',
        'field2' => 'numeric',
        // Add more validation rules for other fields
    ]);

    if ($validator->fails()) {
        return response()->json(['errors' => $validator->errors()], 400);
    }

    // Proceed with the update logic if validation passes

    // Example: Update the database record
    $record = YourModel::find($id);
    $record->field1 = $request->input('field1');
    $record->field2 = $request->input('field2');
    $record->save();

    return response()->json(['message' => 'Record updated successfully'], 200);
}


In the example above, $request->all() retrieves all the input data sent in the PATCH or PUT request. Modify the validation rules as per your requirements. If the validation fails, the errors will be returned as a JSON response with a 400 status code.

  1. Customize the response as needed based on your application requirements.
  2. Save the changes and test your PATCH or PUT request with different input variations to ensure the validation is working correctly.