How to send validation messages to api in laravel?

Member

by adan , in category: PHP Frameworks , 3 months ago

How to send validation messages to api in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jasen , 3 months ago

@adan 

In Laravel, you can send validation messages to an API by using the validate() method in your controller. Here is an example of how you can do this:

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

public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'name' => 'required',
        'email' => 'required|email',
    ]);

    if ($validator->fails()) {
        return response()->json([
            'error' => $validator->errors()
        ], 422); // 422 status code for validation error
    }

    // If validation passes, proceed with your logic
}


In the above example, we are validating the name and email fields in the request. If the validation fails, we return a JSON response containing the validation errors with a status code of 422. Otherwise, you can proceed with your logic.