3 years ago

About JSON errors response

Posted 3 years ago by sorcjc

Hi. I am using the following code:

    $validator = Validator::make($request->all(), [
            'category_id' => 'required|exists:categories,id',
            'title' => 'required|min:5|max:255',
            'limit' => 'required|integer|min:2|max:25'

        if ($validator->fails())
            return response()->json([
                'success' => false,
                'errors' => $validator->getMessageBag()->toArray()
            ], 400); // HTTP code for an invalid request

        $topic = Topic::create([
            'category_id' => $request->get('category_id'),
            'title' => $request->get('title'),
            'limit' => $request->get('limit'),
            'user_id' => 1

        return response()->json([
            'success' => true,
            'topic' => $topic
        ], 200);

When the validation fails, it response with a JSON like this:

  "success": false,
  "errors": {
    "limit": [
      "The limit must be at least 2."

As you can see, the "limit" field is an array. My question is, why it is an array instead of a simple string? I was trying to generate more errors for that field but I can't. Is it possible to get just one string as value for each field?

I read about "Transformers", but it seems too complicated. I don't need to create custom responses for each model. I just want to modify the format of the error bag when it becomes a JSON.

Thanks in advance.

Please sign in or create an account to participate in this conversation.