Feb 23, 2017
0
Level 9
Testing json API post input array
I'm working on a JSON API but I have to send an input array, can't figure out how to test the post method. I want to create an order that has one or more addresses, so I use an array to store them. I tried it in post man and works fine (the name of field in postman was "addresses[0][address]")
This is the code I have on the controller to validate the request.
protected function validateRequest(Request $request)
{
$validator = Validator::make($request->all(), [
'customer_id' => 'required',
'store_id' => 'required',
'order_value' => 'required',
'route_value' => 'required'
]);
$validator->after(function ($validator) use ($request) {
if ($request->addresses) {
foreach ($request->addresses as $key => $value) {
if (!$value['address']) {
if ($key === 0 AND count($request->addresses) === 1) {
$validator->errors()->add('addresses.address', trans('validation.required', ['attribute' => trans('validation.attributes.address')]));
} else if (count($request->addresses) > 1) {
$validator->errors()->add('addresses.' . $key . '.address', trans('validation.required', ['attribute' => trans('validation.attributes.address') . ' ' . ($key + 1)]));
}
}
}
return;
}
$validator->errors()->add('addresses.0.address', trans('validation.required', ['attribute' => trans('validation.attributes.address')]));
});
if ($validator->fails()) {
return response()->json([
'status' => trans('messages.badrequest'),
'results' => $validator->errors(),
], 400);
}
}
the route I use is "/api/orders" and its a POST method. This is the response I get from Postman.
{
"status": "The order has been created correctly.",
"results": {
"customer_id": "1",
"store_id": "1",
"order_value": "1",
"route_value": "1",
"note": null
}
}
And this is the test, and I don't know how to send the address field in the testing environment.
public function store_new_order()
{
$order = factory(Order::class)->make();
$address = factory(Address::class)->make();
$response = $this->actingAs($this->user)->json('POST', 'api/orders', [
'customer_id' => $order->customer_id,
'store_id' => $order->store_id,
'order_value' => $order->order_value,
'booking' => $order->booking,
'addresses' => $address,
])->assertStatus(201);
}
Please or to participate in this conversation.