My json has two objects one is user_profile and other one is privileges but my validation is working only on user_profile object.
My json:
{
"user_profile": {
"email": "shahzad11#ovadamd.com",
"password": "admin123",
"password_confirmation": "admin123",
"status": 0,
"first_name": "Shahzad",
"middle_name": "Hussain",
"last_name": "Shah",
"date_of_birth": "2015-01-01",
"gender": "M",
"area_id": 1,
"address": "Minhatten NY",
"city": "New York",
"state": "Washington",
"zip": "12312",
"fax": "111-111-1111",
"phone_extension": "2471",
"work_phone": "111-111-1111",
"phone_no": "111-111-1111",
"emergency_contact": "111-111-1111",
"social_security": "111-11-1111",
"module_id": 2
},
"privileges": {
"is_super_admin": 1,
"facilities": [
{
"facility_id": 1,
"is_facility_supervisor": 0,
"speciality_id": 1,
"priv_id": "",
"role_id": 1
}
]
}
}
I want to validate my "privileges" object as well.
My controller:
public function register(Request $request) {
$body = $request->all();
$userProfile = $body['user_profile'];
$userPrev = $body['privileges'];
$userProfile['is_super_admin'] = $userPrev['is_super_admin'];
$facilities = $userPrev['facilities'];
$bodyObj = array_merge($userProfile, $userPrev);
$validator = UserValidations::validateUser($bodyObj);
if ($validator->fails()) {
return response([
'status' => false,
'message' => __('messages.validation_errors'),
'errors' => $validator->errors()->all()
], 200);
}
and my validateUser method:
public static function validateUser($data = [], $update = false) {
$rules = [
'first_name' => 'required|max:25',
'last_name' => 'required|max:25',
"address" => 'required|max:197',
"city" => 'required|max:20',
"zip" => 'required|max:5',
"phone_no" => 'required|max:12',
"area_id" => 'exists:areas,id',
"phone_extension" => 'min:3|max:5',
'gender' => 'in:M,F,X',
"work_phone" => 'max:12',
"emergency_contact" => 'max:12',
"fax" => "max:12",
"social_security" => 'required|max:11',
"module_id" => 'exists:modules,id',
// privileges object fields
"role_id" => 'required|exists:roles,id',
"facility_id" => 'required',
"speciality_id" => 'required'
];
if($update) {
$rules['id'] = 'required|exists:users,id';
} else {
$rules['email'] = 'required|email|unique:users';
$rules['password'] = 'required|min:6';
$rules['password_confirmation'] = 'required_with:password|min:6|same:password';
}
return $validator = Validator::make($data, $rules);
}
How i can put validation on privileges object?
Your help will be highly appreciated!
// privileges object fields
"facilities.*.role_id" => 'required|exists:roles,id',
"facilities.*.facility_id" => 'required',
"facilities.*.speciality_id" => 'required'
I think it will solve your problem
you can do this
Validator::make($request->all(),[
'your rules'])
Related
This question already has answers here:
How to extract and access data from JSON with PHP?
(1 answer)
How can I replace a specific key's value in an array in php?
(2 answers)
Closed 7 months ago.
I all, I've been staring at this for hours so any help is greatly appreciated. I have an array...
$aircraft = [
'N7826C' => ['nnum' => 'N7826C', 'name' => 'ANAHEIM POLICE DEPT', 'icon' => 'police', 'lat' => '', 'lng' => '', 'status' => '0'],
'N226PD' => ['nnum' => 'N226PD', 'name' => 'ANAHEIM POLICE DEPT', 'icon' => 'police', 'lat' => '', 'lng' => '', 'status' => '0'],
'N326PD' => ['nnum' => 'N326PD', 'name' => 'CITY OF ANAHEIM', 'icon' => 'police', 'lat' => '', 'lng' => '', 'status' => '0'],
'N826PD' => ['nnum' => 'N826PD', 'name' => 'CITY OF ANAHEIM', 'icon' => 'police', 'lat' => '', 'lng' => '', 'status' => '0']
];
With that array, I implode it to get a list of the nnums to pass through a API....
$aircraftNNUMlist = implode(',', array_map(function($v) { return $v['nnum']; }, $aircraft));
$json = file_get_contents('https://airlabs.co/api/v9/flights?_fields=reg_number,lat,lng®_number='.$aircraftNNUMlist.'&api_key=XXXXX');
That API returns...
{
"request": {
"lang": "en",
"currency": "USD",
"time": 15,
"id": "c9by9lmq1q0",
"server": "z",
"host": "airlabs.co",
"pid": 322387,
"key": {
"id": 19146,
"api_key": "xxxxxxxxxxxxxxxx",
"type": "free",
"expired": "2022-08-20T22:00:00.000Z",
"registered": "2022-07-19T03:51:04.000Z",
"limits_by_hour": 2500,
"limits_by_minute": 250,
"limits_by_month": 1000,
"limits_total": 628
},
"params": {
"_fields": "reg_number,lat,lng",
"reg_number": "N60NT,N40NT,N30NT,N10NT",
"lang": "en"
},
"version": 9,
"method": "flights",
"client": {
"ip": "xxxxxxxxxxxxxxxxx",
"geo": {
"country_code": "US",
"country": "United States",
"continent": "North America",
"city": "Provo",
"lat": 40.2181,
"lng": -111.6133,
"timezone": "America/Denver"
},
"connection": {
"type": "corporate",
"isp_code": 46606,
"isp_name": "Unified Layer"
},
"device": {},
"agent": {},
"karma": {
"is_blocked": false,
"is_crawler": false,
"is_bot": false,
"is_friend": false,
"is_regular": true
}
}
},
"response": [
{
"reg_number": "N60NT",
"lat": 34.11,
"lng": -117.69
}
],
"terms": "Unauthorized access is prohibited and punishable by law. \nReselling data 'As Is' without AirLabs.Co permission is strictly prohibited. \nFull terms on https://airlabs.co/. \nContact us info#airlabs.co"
}
I am having trouble looping through the "response" of the API return (stored at $json) to update the corresponding index in $aircraft. If a nnum isn't currently active there will not be a entry in "response" for instance "response" only has N60NT in the return array. I am fairly new to arrays so I've been taking swings in the dark and nothing seems to be right.
I presume you have json_decoded your api json response into a PHP array. Well actually:
$arr = json_decode($json_form_api, true);
$response = $arr["response"];
foreach ($response as $sub) {
$reg = $sub["reg_number"];
$aircraft[$reg]["lat"] = $sub["lat"];
$aircraft[$reg]["lng"] = $sub["lng"];
}
I have this php code as I am trying to execute a particular function in my php project, I code the implementation correct but I ran into a small problem.
<?php echo '<script type="text/javascript">';
$data = array(
'base' => 'USD',
'alter' => 'ETH',
'data' => array()
);
foreach ($cryptos as $row) {
$sy = $row["symbol"];
$data['data'][] = array(
"$sy" => [
"rate" => 1.552000000000000,
"min" => 1.0077600000000000,
"max" => 10.077600000000000,
"code" => $row["symbol"],
"dp" => 8
],
);
}
print_r("var fxCur = " . json_encode($data));
Running the code above I got this result below, That's the expected result but I want to omit [] between data
{
"base":"USD",
"alter":"ETH",
"data":[
{
"BTC":{
"rate": 1.552000000000000,
"min": 1.0077600000000000,
"max": 10.077600000000000,
"code":"BTC",
"dp":8
}
},
{
"ETH":{
"rate": 1.552000000000000,
"min": 1.0077600000000000,
"max": 10.077600000000000,
"code":"ETH",
"dp":8
}
}
]
}
But actually I wanted this result
{
"base":"USD",
"alter":"ETH",
"data":{
"BTC":{
"rate": 1.552000000000000,
"min": 1.0077600000000000,
"max": 10.077600000000000,
"code":"BTC",
"dp":8
},
"ETH":{
"rate": 1.552000000000000,
"min": 1.0077600000000000,
"max": 10.077600000000000,
"code":"ETH",
"dp":8
},
}
}
You're telling it to construct the data structure that way.
$data['data'][] = array(
"$sy" => [
...
]
);
That line says "append an element to $data['data'] at the next integer index and set it equal to the array e.g. [ "BTC" => [ ... ]]
I think what you want is:
$data['data'][$sy] = [
"rate" => 1.552000000000000,
"min" => 1.0077600000000000,
"max" => 10.077600000000000,
"code" => $row["symbol"],
"dp" => 8
];
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 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