Looping through validation data received from Ajax in laravel controller - php

I am sending a json request through Ajax, this request contains multiple objects,I am trying to find a way to validate the request to fail if at least one particular attribute fails the rule(min 5 characters in "value"); but dosent seems to work, can anyone help ?
I tried to loop data , I feel I am close but still dosent work.
my Ajax:
-------
< script >
function ajaxUpdate() {
var formdata = document.getElementsByTagName('input');
var formT = [].map.call(formdata, function(input) {
if (input.style.textDecoration === "line-through") {
input['completed'] = "1"; //add key value pairs
} else {
input['completed'] = "0"; //add key value pairs
}
return {
'value': input.value,
'id': input.id,
'completed': input.completed
}; //determine what keys to show.
});
formT.shift(); // Removes the first element from an array, because it contains token
formT = formT.filter(function(e) {
return e != null; //remove null elements.
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// e.preventDefault();
$.ajax({
url: "/updateAddTask",
dataType: "json",
contentType: "application/json",
data: {
objJSON: JSON.stringify(formT),
},
success: function(response) {
if ($.isEmptyObject(response.error)) {
if (response.success === true) {
successSweetAlert();
} else {
alert(JSON.stringify(response.errors.value.toString()));
}
}
},
// location.reload();
})
}
</script>
My controller:
--------------
public function loopData(Array $data)
{
foreach ($data as $key => $jsons) {
foreach ($jsons as $key1 => $value) {
return $jsons;
}
}
}
public function ajaxUpdateTasks(Request $request)
{
$data = json_decode($request->objJSON, true);//this will give an array of all the input elements
// dd($data);//output is below:
// array:3 [
// 0 => array:3 [
// "value" => "kilo"
// "id" => "55"
// "completed" => "0"
// ]
// 1 => array:3 [
// "value" => "new123"
// "id" => "793"
// "completed" => "1"
// ]
// 2 => array:3 [
// "value" => "ef4"
// "id" => "794"
// "completed" => "0"
// ]
//]
$rules = [
'value' => 'required|max:255|min:5', //value is
];
$messages = [
'value.max' => 'Todo title should be less than 255 characters',
'value.min' => 'Todo title should be more than 4 characters'
];
$validator = Validator::make($this->loopData($data),$rules, $messages);// ?????
if ($validator->fails()) {
$errors = $validator->getMessageBag()->toArray();
$result = ['success' => false, 'errors' => $errors];
return response()->json($result);
} else {
$result = ['success' => true, 'errors' => null];
$count = count(json_decode($request->objJSON, true));
$id = json_decode($request->objJSON, true)[0] ['id'];
$value = json_decode($request->objJSON, true)[0] ['value'];
$completed = json_decode($request->objJSON, true)[0] ['completed'];
-----remaining of the code --------
}
Thanks for any help.

I solve it by simply changing rules and messages: $rules = [ " *.value" => 'min:4', ]; $messages = [ " *.value.max" => 'Todo title should be less than 255 characters', " *.value.min" => 'Text should be more than 4 characters' ]; $validator=Validator::make($data, $rules,$messages);

Related

Why does my foreach-loop outputs only one checklistItem? (PHP)

My aim is to get an array of all userChecklistItems but the loop only returns one value. I think it has something to do with the category-array but I can't find a solution...
private $responseJson = [];
public function getArray($user) {
$responseJson['checklistItems'] = [
ChecklistItem::CATEGORY_DAY => [],
ChecklistItem::CATEGORY_WEEK => [],
ChecklistItem::CATEGORY_MONTH => [],
ChecklistItem::CATEGORY_ONE_HUNDRED_DAYS => []
];
$userChecklistItems = $user->getUserChecklistItems();
foreach($userChecklistItems as $userChecklistItem) {
$category = $userChecklistItem->getChecklistItem()->getCategory();
$responseJson['checklistItems'][$category] = [
'text' => $userChecklistItem->getChecklistItem()->getText(),
'isChecked' => $userChecklistItem->getIsChecked()
];
};
return $responseJson;
}
Ok, I got it - the newArray was missing
$userChecklistItems = $user->getUserChecklistItems();
$newArray = [];
foreach($userChecklistItems as $userChecklistItem) {
$category = $userChecklistItem->getChecklistItem()->getCategory();
$responseJson['checklistItems'][$category] = [
'text' => $userChecklistItem->getChecklistItem()->getText(),
'isChecked' => $userChecklistItem->getIsChecked()
];
$newArray[] = $responseJson;
};
return $newArray;

Get key value from multidimensional array not working

I am trying to get a value from a multidimensional array by its name 'code'. When I dump and die the first way it returns the correct value. When I then want to use that in the code, it gives the error "Undefined index: code". I also used the array_column way, that dd an empty array.
The code that should get the correct $code:
foreach ($houses as $house) {
$code = $house['code']; //Returns correct value in a dd, not in the code
$code = array_column($house, 'code'); //Returns empty array in dd, later gives the error Array to string conversion in the file_get_contents
$a = file_get_contents('some-url' . $code . '/surveys');
$a = json_decode($a, true);
$surveys = $a['surveys'];
$completedSurveys = $a['surveysCompleted'];
$done = 0;
$ndone = 0;
foreach ($completedSurveys as $complete) {
if($complete) {
$done++;
} else if(!$complete) {
$ndone++;
} else {continue;}
}
}
$house dump:
array:30 [
id: ''
project: integer
city: ''
streetName: ''
houseNumber: ''
code: ''
fullStreet: ''
forms: array:1 [
0: integer
]
]
$code dump
$house['code']: "AB12-CD34-EF56-GH78"
array_column($house, 'code'): []
I would like to know the solution to this so that I can use the $code in the url to get the correct things back from the api.
You can use array_column on your entire array, not the sub-arrays.
$houses =
[
[
'code' => '23',
'city' => 'Dublin'
],
[
'city' => 'Canberra'
],
[
'code' => '47',
'city' => 'Amsterdam'
]
];
var_export(array_column($houses, 'code'));
Output:
array (
0 => '23',
1 => '47',
)
You could then do something along these lines.
$get_survey = function ($code) {
if($response = file_get_contents("http://example.com/$code/surveys"))
if($json = json_decode($response, true))
return $json;
};
$completed = [];
foreach(array_column($houses, 'code') as $code) {
if($survey = $get_survey($code)) {
// survey count calculation.
} else {
$completed[$code] = null; // failure to get survey data.
}
}

Laravel PHP filter multidimensional array by multiple key values

I have an array that looks like this:
[
[
"type" => "dir",
"path" => "vendor/test/test",
"dirname" => "vendor/test",
"basename" => "test",
"filename" => "test",
],
[
"type" => "file",
"path" => "vendor/test/test.html",
"visibility" => "public",
"size" => 0,
"dirname" => "vendor/test",
"basename" => "test.html",
"extension" => "html",
"filename" => "test",
],
[
"type" => "file",
"path" => "vendor/test/test2.html",
"visibility" => "public",
"size" => 0,
"dirname" => "vendor/test",
"basename" => "test2.html",
"extension" => "txt",
"filename" => "test2",
]
]
I want to have an array with only the arrays where type equals "file" and extension equals "html"
This is what I have so far and works great for 1 filter only
$filter = ['file'];
$contents = array_filter($contents, function ($event) use ($filter) {
return in_array($event['type'], $filter);
});
If I try to put multiple values in the filter and in the in_array function it complains.
How can I use 2 filters?
You can simply get it like this:
$result = [];
foreach ($contents as $item) {
if (in_array('type', $item)) {
if ($item['type'] === 'file') {
if (in_array('extension', $item)) {
if ($item['extension'] === 'html') {
$result[] = $item;
}
}
}
}
}
// dd($result)
you can try this
// setting a filter for each key we want
$filters = ['extension'=>['html'],'type'=>['file','dir']];
$contents = array_filter($contents, function ($event) use ($filters) {
// checking for each filter inside the associative array
foreach($filters as $key => $filter){
// assuming $key is type and $filter is file,dir
// if type isn't file or dir it'll remove the event from the contents
if(!in_array($event[$key], $filter){
return false;
}
}
return true;
});
You can do it like this:
$contents = array_filter($contents, function ($event) {
return isset($event['type']) &&
isset($event['extension']) &&
$event['type'] === 'file' &&
$event['extension'] === 'html';
});
Laravel style alternative:
https://laravel.com/docs/5.8/helpers#method-array-where
$filtered = Arr::where($array, function ($value, $key) {
return $value['type'] === 'file' && $value['extension'] === 'html';
});
you can try this way :
$contents = array_filter($contents, function ($event){
return $event['type']=='file' && $event['extension']=='html';
});
or
$filter=['file','html'];
$contents = array_filter($contents, function ($event) use ($filter) {
return $event['type']==$filter[0] && $event['extension']==$filter[1];
});

Invalid JSON Response in Datatable Codeigniter

I need an expert to fix this . This is my controller that load JSON .
foreach ($result->result() as $row){
$customer = $row->customer_name;
$ipull = $row->ip;
if ($this->mikrotikext->mikrotik_connect($ip,$username,$password,$port) == true){
$PING = $this->routerosapi->comm("/ping", array(
"address" => $ipull,
"count" => "2"
));
if( $PING['0']['packet-loss'] == 0){
$status = "Online";
} else {
$status = "Offline";
}
} else {
$this->session->set_flashdata('Connect_False','Failed To get');
redirect('tmikrotik/router_list');
}
$data = array(
'customer' => $customer,
'address' => $ipull,
'status' => $status
);
print json_encode($data);
}
And this is JSON response:
{"customer":"Trakindo Utama","address":"192.168.1.3","status":"Online"}{"customer":"Adira Finance","address":"192.168.1.10","status":"Offline"}{"customer":"Mandala Finance","address":"192.168.1.50","status":"Online"}
The problem is, when I load it into my data table, show popup invalid JSON response. This is my jQuery code
$(function () {
var table = $("#cpe-status").DataTable({
fixedColumns: true,
fixedHeader: true,
"pageLength": 10,
"paging": true,
"ajax": {
url: "./cpe",
type: "GET",
dataSrc: ""
},
"scrollX": true,
"aoColumns": [
{"data": "customer", "title": "Host"},
{"data": "address", "title": "Customer Name"},
{"data": "status", "title": "Registered"}
// {"data": "status", "title": "Status"}
]
});
// setInterval(function () {
// table.ajax.reload();
// }, 10000);
})
You are printing each result inside the loop. You should print the result as 1 array.
/* ============= Declare the data outside the loop ============= */
$data = array();
foreach ($result->result() as $row){
$customer = $row->customer_name;
$ipull = $row->ip;
if ($this->mikrotikext->mikrotik_connect($ip,$username,$password,$port) == true) {
$PING = $this->routerosapi->comm("/ping", array(
"address" => $ipull,
"count" => "2"
));
if( $PING['0']['packet-loss'] == 0){
$status = "Online";
} else {
$status = "Offline";
}
} else {
$this->session->set_flashdata('Connect_False','Failed To get');
redirect('tmikrotik/router_list');
}
/* ============= Push each result on an array ============= */
$data[] = array(
'customer' => $customer,
'address' => $ipull,
'status' => $status
);
}
/* ============= print result (outside the loop ) ============= */
print json_encode($data);

Getting Error with result

success: function(response){
$('#ul').html("");
var obj = JSON.parse(response);
public function autocomplete(){
$search = $this->input->post('search');
$query = $this->get_apartments($search);
echo json_encode ($query);
}
public function get_apartments($search)
{
$query = [
'val' =>'*',
'table' => 'tbl_apartments as apt',
'where' => [],
'orderby' => 'apt.id',
'orderas' => 'desc',
'in_value'=> '',
'like' => ['likeon' => 'apt.apt_no', 'likeval' => $search]
];
$datasss = [
['table' => 'coach as bd' , 'on' => "bd.bd_code = apt.bd_code", 'join_type'=>'inner']
];
$result = $this->common->datasss_with_in($query,$multijoin);
}
When I am Using To print_r($result); exit; to see the result it
showing me the result but when i commented this line its showing me
that obj is null... why this happening
get_appartments() should return something:
return $result;
so $query will get a value.
check what you receive in javascript using
console.log(response);
success: function(response) {
$('#ul').html('');
for(var $i=0;$i<$response.rows.length;$i++) {
$('#ul').append('<li>' + response.rows[$i].building_name + '<li>');
}
}
i found the answer i need to return $result['rows]; simple solution cos json not accepting complete inm y case

Categories