How to validate and insert array of objects in php? - laravel

I want to validate and insert array of object into my database. This is my array of objects: (Front end js)
studentData: [
{id: 1, name: 'Juan'},
{id: 2, name: 'Jema'},
]
This is my current code for StudentController.php:
for($i; $i <= count($request->input()); $i++){
$student = Student::create([
'id' => $request[$i]["id"],
'name' => $request[$i]["name"],
]);
}
and this works perfectly when I'm inserting all my object. Now, I want to validate all the request. This code is not working:
$validate = $request[$i]->validate([
'id' => 'required|unique:students|numeric'
]);
for($i; $i <= count($request->input()); $i++){
$validate = $request[$i]->validate([
'id' => 'required|unique:students|numeric'
]); //this is the error. I cant validate the data foreach user
$student = Student::create([
'id' => $request[$i]["id"],
'name' => $request[$i]["name"],
]);
}

You have to do array input validation with dot like this:
$this->validate($request,[
'studentData.*.id' => 'required|unique:students|numeric',
'studentData.*.name' =>'required'
],
$messages = [
// write error messages
]);
I hope you will understand.
You can see laravel docs for array input validation here https://laravel.com/docs/5.6/validation#validating-arrays

Related

Problems with Laravel data validation

I'm having some problems with validations in my api.
I need to send a json array like this:
[
{
"acktime": "2021-09-25 08:45:07",
"temp": 15.6
},
{
"acktime": "2021-09-25 08:45:07",
"temp": 15.6
}
probably more array....
]
I would like to vaidate one by one array and store only the valid data returning error for unvalid data, I have tried a foreach cylce but it convert the array to object but the validate::make want only array.
I have tried this:
$validator = Validator::make($request->all(), [
'*.acktime' => 'required',
'*.temp' => 'required|numeric'
]);
$validatedData = $validator->validated();
var_dump($validatedData);
return response()->json($validatedData);
But If I send wrong data I get only error without having valid data, so I've tried this way:
foreach($datas as $data){
$arr = (array)$data;
$validator = Validator::make($arr, [
'acktime' => 'required',
'temp' => 'required|numeric'
]);
if ($validator->fails()) {
continue;
} else {
$newrawData = new rawData([
'acktime' => $data->acktime,
'temp' => $data->temp,
'synctime' => now()
]);
$newrawData->save();
}
}
return response('OK', 200); //or error if some data are not ok
}
In this way it work, bot I have no idea about get, a probable, validation error..(for the moment there's a continue for continue the cycle) any suggestion?
There are two ways for approaching this kind of validation:
make a custom rule in laravel validation from below and put your validation code in it and this will work:
https://laravel.com/docs/8.x/validation#custom-validation-rules
easier way:
$data = [ 'data' => $requests->all() ];
$validator = Validator::make($data, [
'data.*.name' => 'required|string',
'data.*.' => 'required|string'
]);

POST, Response and assertJson in phpunit testing

I have following test function to check the update data is correct or not.
It has no problem in updating.
My question is how to check the given parameters are correct after updated.
for example
if response.id == 1 and response.name = 'Mr.Smith'
assertcode = OK
else
assertcode = NG
public function user_update_info(){
$this->post('login',['email' => config('my-app.test_user'),
'password' => config('my-app.test_pass')]);
$response = $this->post('/update_info',[
'id' => 1,
'name' => 'Mr.Smith',
'post_code' => '142-4756',
'prefectural_code' => '15',
'address' => 'Merchat St.',]);
$response->assertStatus(200);
}
Assume your update_info route update User model.
Try below after your code,
$user = User::find(1);
static::assertTrue($user->id == 1 && $user->name = 'Mr.Smith');
To check if the response returns a json data you expect, you can use assertJson() method of the response object like so:
$response->assertJson([
'id' => 1,
'name' => 'Mr.Smith'
]);

Map array values to collection of items

How would one do the following elegantly with laravel collections ?
Map the values of the $baseMap as keys to the collection.
The baseMap :
$baseMap = [
'name' => 'new_name',
'year' => 'new_year',
];
The collection :
$items = collect([
[
'name' => 'name1',
'year' => '1000',
'not_in_basemap' => 'foo'
],
[
'name' => 'name2',
'year' => '2000',
'not_in_basemap' => 'foo'
],
//...
]);
The end result :
$result =[
[
'new_name' => 'name1',
'new_year' => '1000',
],
[
'new_name'=> 'name2',
'new_year' => '2000',
],
];
I know how to do it in plain php , just wondering what a nice collection version would be. Thanks!
I tried to find collection methods, or php functions, but without success. Some dirty code that works with different keys from both sides (items and basemap).
$result = $items->map(function($item) use ($baseMap) {
$array = [];
foreach($baseMap as $oldKey => $newKey){
if(isset($item[$oldKey])){
$array[$newKey] = $item[$oldKey];
}
}
return $array;
});
$result = $result->toArray();
Thanks to #vivek_23 and #IndianCoding for giving me idea's I ended up with the following :
I made a small edit to make sure the mapping and the items keys lined up.
so you don't have to worry of misalignment and all in laravel collection !
$baseMap = collect($baseMap)->sortKeys();
$result = $items->map(function ($item) use ($baseMap) {
return $baseMap->values()
->combine(
collect($item)->sortKeys()->intersectByKeys($baseMap)
)
->all();
});
Use intersectByKeys to filter your baseMap keys with $items values.
$result = $items->map(function($item,$key) use ($baseMap){
return array_combine(array_values($baseMap),collect($item)->intersectByKeys($baseMap)->all());
});
dd($result);
Update:
In a pure collection way,
$baseMapCollect = collect($baseMap);
$result = $items->map(function($item,$key) use ($baseMapCollect){
return $baseMapCollect->values()->combine(collect($item)->intersectByKeys($baseMapCollect->all())->values())->all();
});
dd($result);
Here are my two cents, using map. Don't know how dynamic your collection should be, but knowing the keys I would do the following:
$baseMap = [
'name' => 'new_name',
'year' => 'new_year',
];
$items = collect([
[
'name' => 'name1',
'year' => '1000',
'not_in_basemap' => 'foo'
],
[
'name' => 'name2',
'year' => '2000',
'not_in_basemap' => 'foo'
],
])->map(function($item, $key) use ($baseMap) {
return [
$baseMap['name'] => $item['name'],
$baseMap['year'] => $item['year']
];
});

How to set file post properly PhpUnit

I'm trying to set a test to upload a file.
In the controller I need to check if everyting is ok (form validation).
The problem is the response gives me an error $request->dataFile->getClientOriginalExtension() , (vendor/symfony/http-foundation/File/UploadedFile.php)
Looks like the dataFile, or request or.... I dont know how to set it.
/**
#test
#group formPostFile
*/
public function formPostFile()
{
$test_file_path = base_path().'/httpdocs/test/Excel.xlsx';
$this->assertTrue(file_exists($test_file_path), $test_file_path.' Test file does not exist');
$_FILE = [
'filename' => [
'name' => $test_file_path,
'type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'size' => 10336,
'tmp_name' => $test_file_path,
'error' => 0
]
];
$data = [
'id' => '2',
'dataFile' => $_FILE
];
$response = $this->post('/excel', $data);
dd($response->getContent());
}
Utilise the Symfony/Illuminate class UploadedFile
$file = new UploadedFile(
$test_file_path,
$test_file_path,
filesize($test_file_path),
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
null,
true
);
LastParameter is testMode and should be true, i believe this will work out in your code, utilise it in a similar fashion as the array you already have like so.
$data = [
'id' => '2',
'dataFile' => $file
];

Avoid duplication in doctor_id field with where clause in laravel 5.4

this is my doctors id
this is my user id
I can't insert anything when I put unique in the validation of doctor_id. When there's no unique it works fine.
I want to avoid duplicate doctor_id where auth::id == 1. Any advice is appreciated.
public function store(Request $request, $id)
{
$auth = Auth::id();
$constraints = [
'doctor_id' => 'required|unique',
'day1' => 'required|max:20',
'day2'=> 'required|max:60',
'day3' => 'required|max:60'
];
$input = [
'users_id' => $auth,
'doctor_id' => $id,
'day1' => $request['day1'],
'day2' => $request['day2'],
'day3' => $request['day3'],
'day4' => $request['day4'],
...
'day27' => $request['day27'],
'status' => '1'
];
$this->validate($request, $constraints);
Itinerary::create($input);
$added = array('added'=> 'Added Doctor to Itinerary Successful!!');
return redirect()->back()->with($added);
Have you tried this? (assuming your table is named itineraries):
'doctor_id' => 'unique:itineraries'
According to Laravel Doc, you should add the table name, and column name if possible:
unique:table,column,except,idColumn

Resources