Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validation with custom json respons

Quick question. Would it be possible to changes the JSON validation response of laravel? This is for a custom API that I am building in Laravel.

Validation process

$validation = $this->validate( 
    $request, [
        'user_id' => 'required', 
    ]);

The response shows up like this in json

{
  "message": "The given data was invalid.",
  "errors": {
    "user_id": [
      "The user id field is required."
    ],
  }
}

Preferable it would become something like this.

{
    "common:" [
        "status": "invalid",
        "message": "Param xxxx is required",
    ],
}

What would be the best way to changes this? Is it even possible?

Thank you.

like image 490
Wesley Schravendijk Avatar asked Oct 16 '22 06:10

Wesley Schravendijk


1 Answers

You can do this, and it will be reflected globally. Navigate to below folder and use Controller.php app/Http/Controllers

use Illuminate\Http\Request;

Write below method in Controller.php and change response as you want.

public function validate(
    Request $request,
    array $rules,
    array $messages = [],
    array $customAttributes = [])
{
    $validator = $this->getValidationFactory()
        ->make(
            $request->all(),
            $rules, $messages,
            $customAttributes
        );
    if ($validator->fails()) {
        $errors = (new \Illuminate\Validation\ValidationException($validator))->errors();
        throw new \Illuminate\Http\Exceptions\HttpResponseException(response()->json(
            [
                'status' => false,
                'message' => "Some fields are missing!",
                'error_code' => 1,
                'errors' => $errors
            ], \Illuminate\Http\JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
    }
}

I have tried it with Laravel 5.6, maybe this is useful for you.

like image 149
Dev Ramesh Avatar answered Oct 21 '22 00:10

Dev Ramesh