ahoi
1 month ago
324
1
Laravel

Return custom error on Model::create

Posted 1 month ago by ahoi

Hello everybody,

I would like to do the following: A new model should be created by posting the data via API to another server.

The response is a Illuminate\Http\JsonResponse.

This is what I am doing at the moment:

    public static function create($data)
    {
        /*Create a new item using the API*/
        $client = new ApiClient();

        $response = $client->postToApi('/api/item', $data);

        if ($response->getStatusCode() !== 200) {
            return $response;
        }

        return json_decode((string)$response->getBody())->data;
    }

If the submission succeeds, the following response is returned (which is the output of json_decode((string)$response->getBody())->data ):

{#1046
  +"id": 10
  +"country": "de"
  +"homepage": null
  +"status": "active"
}

If the action fails, I am getting this object:

Illuminate\Http\JsonResponse {#1038
  #data: ""{\"message\":\"The given data was invalid.\",\"errors\":{\"data.id\":[\"data.id is not unique.\"]}}""
  #callback: null
  #encodingOptions: 0
  +headers: Symfony\Component\HttpFoundation\ResponseHeaderBag {#1037
    #computedCacheControl: array:2 [
      "no-cache" => true
      "private" => true
    ]
    #cookies: []
    #headerNames: array:3 [
      "cache-control" => "Cache-Control"
      "date" => "Date"
      "content-type" => "Content-Type"
    ]
    #headers: array:3 [
      "cache-control" => array:1 [
        0 => "no-cache, private"
      ]
      "date" => array:1 [
        0 => "Tue, 07 Apr 2020 14:11:01 GMT"
      ]
      "content-type" => array:1 [
        0 => "application/json"
      ]
    ]
    #cacheControl: []
  }
  #content: ""{\"message\":\"The given data was invalid.\",\"errors\":{\"data.id\":[\"data.id is not unique.\"]}}""
  #version: "1.0"
  #statusCode: 422
  #statusText: "Unprocessable Entity"
  #charset: null
  +original: "{"message":"The given data was invalid.","errors":{"data.id":["data.id is not unique."]}}"
  +exception: null
}
=> Illuminate\Http\JsonResponse {#1038
     +headers: Symfony\Component\HttpFoundation\ResponseHeaderBag {#1037},
     +original: "{"message":"The given data was invalid.","errors":{"data.id":["data.id is not unique."]}}",
     +exception: null,
   }

Alright, I can work with this. But: Is there any possibility to make this response more "compatible" to default eloquent models (in success and in failure)?

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