6

I'm trying to implement validation in my api like this:

public function store(RideUpdateRequest $request)
    {
        $user = JWTAuth::parseToken()->authenticate();

        $ride = Ride::create([
            'user_id'       => $user->id,
            'time'          => $request->time,
            'date'          => $request->date,
            'type_id'       => $request->type_id,
            'location_id'   => $request->location_id,
            'billabletime'  => $request->billabletime
        ]);

        $ride->save();

        return response()->json(['success' => 'Rit succesvol aangemaakt.'], 200);
    }

RideUpdateRequest:

 public function rules()
    {
        return [
            'time'             =>  'required|integer',
            'date'             =>  'required|date',
            'type_id'          =>  'required|integer',
            'location_id'      =>  'required|integer',
            'billabletime'     =>  'required|integer'
        ];
    }

So how could I give a error message back in json (if the request validation fails)? Right now in postman I receive nothing back?

--EDIT--

response:

{
  "billabletime": [
    "The billabletime field is required."
  ]
}

Could I get something like this?:

    {
      "error": {
        "The billabletime field is required."
      }
    }

3 Answers 3

13

If you take a look at the FormRequest class, you'll see a response() method defined as something like:

public function response(array $errors)
{
    if ($this->expectsJson()) {
        return new JsonResponse($errors, 422);
    }
    ...
}

So you can either set an Accept: aplication/json request header to comply with the expectsJson condition, or force the default response behavior by sepcifying the response() method in your own RideUpdateRequest class:

public function response(array $errors)
{
    // Always return JSON.
    return response()->json($errors, 422);
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks! One more question right now I receive it not like an object. Is that possible? See my edit for what I mean. Thankyou
You can try this: return response()->json(['error' => $errors], 400);
7

In laravel 8 you can control the response by overriding the failedValidation function in your FormRequest class:

use Illuminate\Http\Response;

protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
{
    $response = new Response(['error' => $validator->errors()->first()], 422);
    throw new ValidationException($validator, $response);
}

2 Comments

I am checking how Laravel 8 handle with api validation, thanks for the tips
Another tip is when u send API request, the header need to add accept:application/json, then it will automatic to return json.
1

response:

{
  "billabletime": [
    "The billabletime field is required."
  ]
}

Could I get something like this?:

{
  "error": {
    "The billabletime field is required."
  }
}

Laravel uses this format because a) there may be multiple fields that fail validation and b) there may be multiple failures for a particular field.

For example:

{
  "email": [
    "The email field is invalid."
  ],
  "password": [
    "The password field must contain a number.",
    "The password field must contain a special character."
  ]
}

Your "error": { ... } is also unnecessary, because Laravel's validation system sends a 422 Unprocessable Entity status code with the response.

2 Comments

Oke I understand that. But in my angular app It's very difficult to use that format.
@Jamie Then you'll need to decide which of the multiple errors get sent back.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.