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." } }
Advertisement
Answer
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); }