I'm trying to validate data gathered from a json file. If I don't include the "required" validation, the validation passes, but when I add it back in it fails for some reason. I don't understand how it would be failing if all fields it's checking against aren't null.
Anything obvious that I'm missing?
Controller:
// START: Validate request
$validator = Validator::make($request->all(), [
'results.*.status.*.name' => 'required|max:255',
'results.*.error.*.name' => 'required',
'results.*.messageId' => 'required',
'results.*.doneAt' => 'required|date',
'results.*.smsCount' => 'required|numeric',
'results.*.sentAt' => 'required',
'results.*.callbackData' => 'required',
]); // The "required" is causing the validation to fail
if ($validator->fails()) {
dd('fail');
} else {
dd('pass');
}
// END: Validate request
Json data:
{
"results": [
{
"bulkId": "BULK-ID-123-xyz",
"price": {
"pricePerMessage": 0.0185,
"currency": "GBP"
},
"status": {
"id": 5,
"groupId": 3,
"groupName": "DELIVERED",
"name": "DELIVERED_TO_HANDSET",
"description": "Message delivered to handset"
},
"error": {
"id": 0,
"name": "NO_ERROR",
"description": "No Error",
"groupId": 0,
"groupName": "OK",
"permanent": false
},
"messageId": "MESSAGE_UUID",
"doneAt": "2022-11-21T17:11:16.661+0000",
"smsCount": 1,
"sentAt": "2022-11-21T17:11:12.129+0000",
"callbackData": "CAMPAIGN_ID",
"to": "447572554668"
}
]
}
You simply just have to replace this:
'results.*.status.*.name' => 'required|max:255|nullable',
'results.*.error.*.name' => 'required|nullable',
With this:
'results.*.status.*' => 'required|max:255|nullable',
'results.*.error.*' => 'required|nullable',
You are getting error because of there is no name key in status properties and you want them to be required.
Related
I'm trying to update user through api, and this is the function.
PUT request http://20a11140.ngrok.io/api/userregister/24 for user with id 24 for example.
I'm using postman for testing
When I pass the edited details, with name inclusive
public function update(Request $request, $id)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'string|min:6|confirmed',
'phone' => 'string|min:6',
'Age' => 'string',
'Blood' => 'string',
'Gender' => 'string',
'Height' => 'string',
'Weight' => 'string',
'record' => 'string'
]);
if($validator->fails()){
return response()->json($validator->errors()->toJson(), 400);
}
$doc = User::find($id);
if($request->hasFile('picture')){
// Get filename with the extension
$filenameWithExt = $request->file('picture')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('picture')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('picture')->storeAs('public/images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
$doc->name = $request->input('name');
$doc->email = $request->input('email');
$doc->phone = $request->input('phone');
if($request->hasFile('picture')){
$doc->picture = $fileNameToStore;
}
$doc->save();
return response()->json([
'message' => 'Success',
]);
}
When I pass the edited details, with name inclusive and email, and every required info.
When I run this code, I get this
"{\"name\":[\"The name field is required.\"],\"email\":[\"The email field is required.\"]}"
What is the issue here?
Somewhere you are wrong with sending data.
If you are using API middlewares then you will have to send data with Body Raw Json using Postman.
{
"info": {
"_postman_id": "9bc0d91b-83e7-4ccf-a561-ac191c21e869",
"name": "Laravel",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "http://20a11140.ngrok.io/api/userregister/24",
"request": {
"method": "PUT",
"header": [
{
"key": "Content-Type",
"name": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\n\t\"name\" : \"BHaskar Rajoriya\",\n\t\"email\" : \"brn.rajoriya#gmail.com\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "http://20a11140.ngrok.io/api/userregister/24",
"protocol": "http",
"host": [
"20a11140",
"ngrok",
"io"
],
"path": [
"api",
"userregister",
"24"
]
}
},
"response": []
}
],
"protocolProfileBehavior": {}
}
Use this postman collection.
I want to do paging at the Laravel API. As a result, I want to get data and status code type.
Controller :
public function index()
{
$data = PersonCollection::collection(Person::paginate(2));
return response()->json($data, 200);
}
PersonCollection Resource :
public function toArray($request)
{
return [
'id' => $this->id,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'email' => $this->email,
'phone' => $this->phone,
'city' => $this->city,
'href' => [
'link' => route('person.show', $this->id),
],
];
}
Output :
https://i.hizliresim.com/LvlBzj.png
[
{
"id": 1,
"first_name": "Burak Ali",
"last_name": "Ildır",
"email": "burak#gmail.com",
"phone": "376.395.7233",
"city": "Koelpinstad",
"href": {
"link": "http://127.0.0.1:8000/api/v2/person/1"
}
},
{
"id": 2,
"first_name": "Vena",
"last_name": "Spinka",
"email": "shields.carolyn#example.org",
"phone": "716-268-7788 x092",
"city": "South Gudrunbury",
"href": {
"link": "http://127.0.0.1:8000/api/v2/person/2"
}
}
]
But I want.
https://i.hizliresim.com/LvlBWo.png
{
"data": [
{
"id": 1,
"first_name": "Burak Ali",
"last_name": "Ildır",
"email": "burak#gmail.com",
"phone": "376.395.7233",
"city": "Koelpinstad",
"href": {
"link": "http://127.0.0.1:8000/api/v2/person/1"
}
},
{
"id": 2,
"first_name": "Vena",
"last_name": "Spinka",
"email": "shields.carolyn#example.org",
"phone": "716-268-7788 x092",
"city": "South Gudrunbury",
"href": {
"link": "http://127.0.0.1:8000/api/v2/person/2"
}
}
],
"links": {
"first": "http://127.0.0.1:8000/api/v1/person?page=1",
"last": "http://127.0.0.1:8000/api/v1/person?page=26",
"prev": null,
"next": "http://127.0.0.1:8000/api/v1/person?page=2"
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 26,
"path": "http://127.0.0.1:8000/api/v1/person",
"per_page": 2,
"to": 2,
"total": 52
}
}
I want other page links. But when I convert it to JSON data, links and metadata do not come.
A resource collection describes how a collection of models will be transmitted as JSON.
You seem to be using it for an individual model. What you need is:
public function toArray($request)
{
return $this->collection->map(function ($person) {
return [
'id' => $person->id,
'first_name' => $person->first_name,
'last_name' => $person->last_name,
'email' => $person->email,
'phone' => $person->phone,
'city' => $person->city,
'href' => [
'link' => route('person.show', $person->id),
],
];
});
}
However the recommended way is to make a PersonResource instead in the same namespace and implement the toArray($request) in that class:
Person
class Person extends Resource //The name is important
{
public function toArray($request)
{
return [
'id' => $this->id,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'email' => $this->email,
'phone' => $this->phone,
'city' => $this->city,
'href' => [
'link' => route('person.show', $this->id),
],
];
}
}
PersonCollection
class PersonCollection extends ResourceCollection
{
// This class is intentionally empty
}
Finally you should let Laravel handle how to make the response:
public function index()
{
$data = PersonCollection::collection(Person::paginate(2));
return $data->toResponse();
}
The default behaviour of the resource collection is to look for a resource which is named like the collection but with the Collection part removed (in this case PersonCollection will look for a Person resource).
This should ensure each model is converted according to the resource and the pagination behaviour is maintained.
I am using Magento 2.2.2 version. I am trying to update tracking information through their rest API. Here is my code:
$tracking_str =
'{
"items": [
{
"extension_attributes": {},
"order_item_id": "'.$orderItemId.'",
"qty": "'.$qty_invoiced.'"
}
],
"notify": false,
"appendComment": true,
"comment": {
"extension_attributes": {},
"comment": "Item(s) has been shipped",
"is_visible_on_front": 0
},
"tracks": [
{
"extension_attributes": {},
"track_number": "'.$TrackingNumber.'",
"title": "'.$ShipTitle.'",
"carrier_code": "'.$carrierCode.'"
}
],
"packages": [
{
"extension_attributes": {}
}
],
"arguments": {
"extension_attributes": {}
}
}';
I am passing the above things to php curl and for the first time, I am getting a response of shipment id. And the Order status is changing to 'complete' over the Magento API. However, tracking information like carrier code and tracking number are not being updated. When I run the code again, I am getting response as:
res is: stdClass Object
( [message] => Shipment Document Validation Error(s):
The order does not allow a shipment to be created.
You can't create a shipment without products.
)
I don't know, where I am going wrong.
Finally it worked!!!
$tracking_str = [ "items"=> [ [ "order_item_id"=>$orderItemId, "qty"=> $qty_invoiced ] ], "notify" => true, "appendComment" => true, "comment" => [ "extension_attributes" => [], "comment" => "Item(s) has been shipped", "is_visible_on_front" => 0 ], "tracks" => [ [ "extension_attributes" => [], "track_number" => $TrackingNumber, "title" => $ShipTitle, "carrier_code" => $carrierCode ] ] ]
The above code, i have used. some one in github forum's helped me. Thanks to them. Now tracking number, carrier code and title are being updated.
this solution it works for me.
{
"appendComment": true,
"notify": true,
"comment": {
"comment": "shipment creado via webservice",
"is_visible_on_front": 1
},
"tracks": [
{
"track_number": "3SCEMW182389201",
"title": "UPS",
"carrier_code": "Carrier code n"
}
]
}
remove items.
I need to make a POST request to claim voucher. At API docs I find this:
POST /vouchers/{voucherId}/claim
{
"Participant": {
"FirstName": "John",
"LastName": "Jones",
"Telephone": "99999 127 127",
"EmailAddress": "hahahah#hahaha.net",
"PostCode": "HP18 9HX",
"HouseNameNumber": "2",
"Street": "Bridge Road",
"Locality": "Ickford",
"Town": "Lodnon",
"County": "Bucks"
},
"ExperienceDate": "2015-10-01T00:00:00"
}
Now I, using Laravel guzzle library I make this request:
public function testclaim()
{
$client = new GuzzleHttp\Client;
$headers = ['Content-Type' => 'application/json'];
$res = $client->post('https://apidev.asdasd.com/vouchers/11989898_1-9FDD/claim', [
'headers'=>$headers,
'auth' => [
'PET_RES', 'asdasdasd111111'
],
'form_params' => [
'FirstName' => 'Peter',
'LastName' => 'Alexo',
'Telephone' => '8888888888888'
]
]);
$res = json_decode($res->getBody()->getContents(), true);
dd($res);
}
but what I get is:
400 Bad Request
{ "Message": "The request is invalid.", "ModelState": { "claim": [ "An
error has occurred." ] (truncated...)
What is the right way to send a request to the API with following data?
try this
...
'form_params' => [
'Participant' => [
'FirstName' => 'Peter',
'LastName' => 'Alexo',
'Telephone' => '8888888888888'
],
'ExperienceDate' => '2015-10-01T00:00:00'
]
...
if your api just accept json, try replace form_params with json
I did the following rest request and it's working
{
"aggs": {
"gender": {
"terms": {
"field": "gender"
}
}
},
"size": 0
}
But when i do it in PHP with array like this:
['aggs' => [
'gender' => [
'terms' => [
'field' => 'gender'
],
],
],
];
I'm getting the following error :
{
code: 500,
message: ""aggs" is not a valid parameter. Allowed parameters are: "analyzer", "analyze_wildcard", "default_operator", "df", "explain", "fields", "from", "ignore_unavailable", "allow_no_indices", "expand_wildcards", "indices_boost", "lenient", "lowercase_expanded_terms", "preference", "q", "query_cache", "request_cache", "routing", "scroll", "search_type", "size", "sort", "source", "_source", "_source_exclude", "_source_include", "stats", "suggest_field", "suggest_mode", "suggest_size", "suggest_text", "timeout", "version", "fielddata_fields", "filter_path", "client", "custom", "filter_path"",
errors: [ ]
}
I found the solution, it was a problem in the code PHP
We are using a Framework Majora, and we are only returning Queries from ElasticSearch to a response.
So i will fix that for the Aggregation to return aggs in the response.
Thanks