How to validate json data in laravel?

by raphael_tillman , in category: PHP Frameworks , 4 months ago

How to validate json data in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 4 months ago

@raphael_tillman 

In Laravel, you can use the validator class to validate JSON data. Here's an example of how you can validate JSON data in a Laravel controller:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
use IlluminateHttpRequest;

public function validateJson(Request $request)
{
    $data = $request->json()->all();

    $validator = Validator::make($data, [
        'name' => 'required|string',
        'email' => 'required|email',
    ]);

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

    return response()->json(['message' => 'Valid JSON data'], 200);
}


In the above example, we first get the JSON data from the request using $request->json()->all(). Then, we use the Validator::make() method to define the validation rules for the JSON data. If the validation fails, we return a JSON response with the validation errors. If the validation passes, we return a success message.


You can add more complex validation rules and customize the error messages as needed. By using the Laravel validator class, you can easily validate JSON data in your Laravel application.