Can't save Entity Even there is no Errors in CakePhp3 - php

I Have user table and when i want to save it save() return null even when i debug $user there is no error..
'[errors]' => [],
This is my code :
$user = $this->Users->newEntity();
$tmp_hash = md5(rand(0, 1000));
$tmp_id = time();
/* Save individual data */
$user->id = $tmp_id;
$user->first_name = (!empty($user_profile->firstName)) ? $user_profile->firstName : "";
$user->last_name = (!empty($user_profile->lastName)) ? $user_profile->lastName : "";
$user->username = (!empty($user_profile->lastName) && !empty($user_profile->lastName)) ? $user_profile->firstName . "." . $user_profile->lastName : "";
$user->avatar = (!empty($user_profile->photoURL)) ? $user_profile->photoURL : "";
$user->role = "public";
$user->provider = $provider;
$user->provider_uid = $user_profile->identifier;
$user->gender = !empty($user_profile->gender) ? (($user_profile->gender == 'male') ? 'm' : 'f') : "";
$user->email = !empty($user_profile->email) ? $user_profile->email : "";
$user->password = $user_profile->identifier;
$user->link = $user_profile->profileURL;
$user->avatar = $user_profile->photoURL;
//$user->confirm_password = $user_profile->identifier;
$user->tmp_hash = $tmp_hash;
$user->isverified = (!empty($user_profile->emailVerified)) ? 1 : 0;
$user = $this->Users->patchEntity($user, $this->request->data);
debug($user);
$this->Users->save($user);
//debug($this->Users->invalidFields()); // he don't know invalidFields()
How can i show sql statement or something to debug and find the issue ?
die('2');

I found the solution..
The problem is errors() before saving it doesn't contain any message..
But after saving it show the errors..
Liket that:
$this->Users->save($user);
debug($user->errors());
Now i can sees the problems that i have .. these problems is due to unique validation..

Related

POST API Issue - Not functioning

Good afternoon,
I'm having trouble with an api POST request - it simply isn't going anywhere, it's not showing on the API log at all - I've got various get requests which work fine but this one just doesn't - I'm unsure what I am doing wrong.
public function broadband_plan(){
$common = array();
$common['main_menu'] = 'Broadband plan';
$cli_or_postcode = isset($_GET["cli_or_postcode"]) ? $_GET["cli_or_postcode"] : "";
$district_id = isset($_GET["district_id"]) ? $_GET["district_id"] : "";
$sub_premises = isset($_GET["sub_premises"]) ? $_GET["sub_premises"] : "";
$premises_name = isset($_GET["premises_name"]) ? $_GET["premises_name"] : "";
$thoroughfare_number = isset($_GET["thoroughfare_number"]) ? $_GET["thoroughfare_number"] : "";
$thoroughfare_name = isset($_GET["thoroughfare_name"]) ? $_GET["thoroughfare_name"] : "";
$locality = isset($_GET["locality"]) ? $_GET["locality"] : "";
$postcode = isset($_GET["postcode"]) ? $_GET["postcode"] : "";
$nad_key = isset($_GET["nad_key"]) ? $_GET["nad_key"] : "";
$post_town = isset($_GET["post_town"]) ? $_GET["post_town"] : "";
$county = isset($_GET["county"]) ? $_GET["county"] : "";
$district_id = isset($_GET["district_id"]) ? $_GET["district_id"] : "";
$request = array();
$request['apiUsername'] = 'XXXXXXX';
$request['apiPassword'] = 'XXXXXXX';
$request['encryption'] = 'SHA-512';
$request['platform'] = 'LIVE';
$request['method'] = 'POST';
$address = '{
"sub_premises": $sub_premises,
"premises_name": $premises_name,
"thoroughfare_number": $thoroughfare_number,
"thoroughfare_name": $thoroughfare_name,
"post_town": $post_town,
"postcode": $postcode,
"district_id": $district_id,
"nad_key": $nad_key
}';
$address = json_encode($address);
$request['url'] = "/broadband/availability" . $address;
$broadband_plan_detail = array();
if (!empty($address)) {
$broadband_plan_detail = $this->get_plan($request);
}
return view('front.broadband_plan',compact('common','broadband_plan_detail'));
}
The $address after $address = json_encode($address); will be an object, it cannot be concatenated as a string in $request['url'] = "/broadband/availability" . $address;
Please check your API URL and ensure you follow their structure, for example if the API URL accept the parameters as GET request, you can pass the parameters likes:
$request['url'] = "/broadband/availability?sub_premises=" . $sub_premises . "&premises_name=" . $premises_name...
Base on your code, the API method is POST, so you might need to prepare the parameters as an array.

Query data laravel

I want to know how get this working in laravel:
I have two tables: "orders" and "delivery_boys".
When an order is created I want to get "id" in table "delivery_boys" that correspond to the "store_id" in the "order" table.
which looks like that in mysql
SELECT `id` FROM `delivery_boys` WHERE store_id = '3'
Thanks for your help.
I use this function:
protected $table = 'orders';
public function addNew($data)
{
$user = AppUser::find($data['user_id']);
if(isset($data['address']) && $data['address'] > 0)
{
$address = Address::find($data['address']);
}
else
{
$address = new Address;
}
$add = new Order;
$add->user_id = $data['user_id'];
$add->store_id = $this->getStore($data['cart_no']);
$add->d_boy = $add->?????; <---- here i want to add from "delivery_boys" table the "id" that correspond to the "store_id" added just above from the "order" table ---->
$add->name = $user->name;
$add->email = $user->email;
$add->phone = $user->phone;
$add->address = $address->address;
$add->lat = $address->lat;
$add->lng = $address->lng;
$add->address = $address->address;
$add->d_charges = $this->getTotal($data['cart_no'])['d_charges'];
$add->discount = $this->getTotal($data['cart_no'])['discount'];
$add->total = $this->getTotal($data['cart_no'])['total'];
$add->payment_method = $data['payment'];
$add->payment_id = isset($data['payment_id']) ? $data['payment_id'] : 0;
$add->type = isset($data['otype']) ? $data['otype'] : 1;
$add->notes = isset($data['notes']) ? $data['notes'] : null;
$add->save();
run this before $add = new Order;
$d_boy = DB::table('delivery_boys')
->select('id')
->where('store_id', $this->getStore($data['cart_no']))
->first();
and then add it where you need it:
$add->d_boy = $d_boy->id;
$id= DB::table('delivery_boys')->select('id')->where('store_id', '=', $this->getStore($data['cart_no']))->get();

Update posted columns only

I am working with rest API in CodeIgniter
I am working with update API so I want to update only those columns/fields which I sent via postman,
for example, if I sent only first_name and last_name then only these columns should be updated not all columns,
but current code updating all columns, Here is my code where I am wrong?
public function update_userrecords()
{
$add_data['user_id'] = ($this->input->post('user_id') && !empty($this->input->post('user_id'))) ? $this->input->post('user_id') : NULL;
$add_data['first_name'] = ($this->input->post('first_name') && !empty($this->input->post('first_name'))) ? $this->input->post('first_name') : NULL;
$add_data['last_name'] = ($this->input->post('last_name') && !empty($this->input->post('last_name'))) ? $this->input->post('last_name') : NULL;
$add_data['password'] = ($this->input->post('password') && !empty($this->input->post('password'))) ? $this->input->post('password') : NULL;
$t=time();
$data = array(
'first_name'=>$add_data['first_name'],
'last_name'=>$add_data['last_name'],
'password'=>md5($add_data['password']),
'updated_on'=>$t,
);
$this->db->where('id',$add_data['user_id']);
$this->db->update('users', $data);
}
You can use this way
Set you input field in new array and update that array. I have added one field in $insert_data. you can add as much you want.
public function update_userrecords()
{
$add_data['user_id'] = ($this->input->post('user_id') && !empty($this->input->post('user_id'))) ? $this->input->post('user_id') : NULL;
$insert_data = [];
if($this->input->post('first_name') && !empty($this->input->post('first_name'))) {
$insert_data['first_name'] = $this->input->post('user_id');
}
$t=time();
$this->db->where('id',$add_data['user_id']);
$this->db->update('users', $insert_data);
}

Laravel Request does not return result

I am using AWS and laravel 5.1.
I have two issues:
Most of the time API returns the expected result but sometimes server
doesn't return result for longer time. It might be due to the server
load(Although we don't have too much load on server).
Clients wait for few minutes and after that application crashes. Any
Advice.
If Client made an API request and before getting result, if device
loses internet connection. Server has process the data but unable to
deliver it to the client. how to handle this (Both in get as well as
post request)
Sample Code for first Part
public function psychometricResponses(Request $request)
{
$questionId=$request->get('questionId');
$answerId=$request->get('answerId');
$from = $request->has('from');
$userId = $request->has('id') ? $request->get('id') : 0;
$name = $request->has('name') ? $request->get('name') : '';
$email = $request->has('email') ? $request->get('email') : '';
$gender = $request->has('gender') ? $request->get('gender') : '';
$relationshipStatus = $request->has('relationshipStatus') ? $request->get('relationshipStatus') : '';
if($userId!=0){
$status = 1;
User::where('id',$userId)->update(['status'=>1]);
}else{
$status = 0;
}
$id = $this->calculatePersonality($questionId, $answerId, $userId, $from, $name, $email, $gender, $relationshipStatus);
return json_encode(['code'=>200,'message'=>"success",'response'=>array('personality'=>$this->_getPersonality($id),'psychometricId'=>$id,'status'=>$status)]);
}
public function calculatePersonality($questionId, $answerId, $userId, $from, $name, $email, $gender, $relationshipStatus)
{
//
$questionArray = explode(',', $questionId); //arraySize is 60
$answerArray = explode(',', $answerId); // //arraySize is 60
$this->questionAll = $this->_questionAll();
$personality = array('O'=>0,'C'=>0,'E'=>0,'A'=>0,'N'=>0);
for($i=0; $i<sizeof($answerArray);$i++){
$type = $this->_getQuestionType($questionArray[$i]);
if($type=='O'){
$personality['O'] = $answerArray[$i]=='1' ? $personality['O']+1 : $personality['O']-1;
}else if($type=='OR'){
$personality['O'] =$answerArray[$i]=='1' ? $personality['O']-1 : $personality['O']+1;
}else if($type=='C'){
$personality['C'] = $answerArray[$i]=='1' ? $personality['C']+1 : $personality['C']-1;
}else if($type=='CR'){
$personality['C'] = $answerArray[$i]=='1' ? $personality['C']-1 : $personality['C']+1;
}else if($type=='E'){
$personality['E'] = $answerArray[$i]=='1' ? $personality['E']+1 : $personality['E']-1;
}else if($type=='ER'){
$personality['E'] = $answerArray[$i]=='1'?$personality['E']-1 : $personality['E']+1;
}else if($type=='A'){
$personality['A'] = $answerArray[$i]=='1' ? $personality['A']+1 : $personality['A']-1;
}else if($type=='AR'){
$personality['A'] = $answerArray[$i]=='1' ? $personality['A']-1 : $personality['A']+1;
}else if($type=='N'){
$personality['N'] = $answerArray[$i]=='1'? $personality['N']+1 : $personality['N']-1;
}else if($type=='NR'){
$personality['N'] = $answerArray[$i]=='1' ? $personality['N']-1 : $personality['N']+1;
}
}
$mod = array();
$mod['O'] = abs($personality['O']);
$mod['C'] = abs($personality['C']);
$mod['E'] = abs($personality['E']);
$mod['A'] = abs($personality['A']);
$mod['N'] = abs($personality['N']);
arsort($mod);
$values = array_keys($mod);
$pTypeOne = $personality[$values[0]] < 0 ? $values[0].'R' : $values[0];
$pTypeTwo = $personality[$values[1]] < 0 ? $values[1].'R' : $values[1];
$pTypeThree = $personality[$values[2]] < 0 ? $values[2].'R' : $values[2];
$pTypeFour = $personality[$values[3]] < 0 ? $values[3].'R' : $values[3];
$pTypeFive = $personality[$values[4]] < 0 ? $values[4].'R' : $values[4];
$psychometricResponse = PsychometricResponse::create(array('typeA'=>$pTypeOne, 'valueA'=>$personality[$values[0]],'typeB'=>$pTypeTwo, 'valueB'=>$personality[$values[1]],
'typeC'=>$pTypeThree, 'valueC'=>$personality[$values[2]],'typeD'=>$pTypeFour, 'valueD'=>$personality[$values[3]],
'typeE'=>$pTypeFive, 'valueE'=>$personality[$values[4]],'questionId'=>$questionId,'answerId'=>$answerId, 'userId'=>$userId, 'from'=>$from,'name'=>$name,'email'=>$email, 'gender'=>$gender,'relationshipStatus'=>$relationshipStatus));
return $psychometricResponse->id;
}
private function _questionAll(){
$question = PsychometricQuestion::where('isActive',1)->get(['id','type']);
$result =array();
for($i=0;$i<sizeof($question);$i++){
$result[$question[$i]->id] = $question[$i]->type;
}
return $result;
}
private function _getQuestionType($id){
return $this->questionAll[$id];
}
private function _getPersonality($id){
$personality = PsychometricResponse::where('id',$id)->first(['typeA','typeB','typeC','typeD','typeE','valueA','valueB']);
$combined = array($personality->typeA,$personality->typeB);
sort($combined);
$combinedPersonality = PsychometricResult::where('type',$combined[0]."-".$combined[1])->first(['type','keyword','description','colorCode']); //Table PsychometricResult has 40 rows only.
$primaryPersonality = PsychometricResult::where('type',$personality->typeA)->first(['type','keyword','description','colorCode']);
$secondaryPersonality = PsychometricResult::where('type',$personality->typeB)->first(['type','keyword','description','colorCode']);
$permutation = $this->_getAllPermutation($personality);
$stylePersonality = PsychometricStyle::whereIn('type',$permutation)->get(['type','aspect','style','description']);
$primaryPercentage = round(abs($personality->valueA)/(abs($personality->valueA)+abs($personality->valueB)), 2);
$secondaryPercentage = 1 - $primaryPercentage;
return array('primaryPersonality'=>$primaryPersonality,'secondaryPersonality'=>$secondaryPersonality,'combinedPersonality'=>$combinedPersonality,
'styles'=>$stylePersonality,'primaryPercentage'=>$primaryPercentage,'secondaryPercentage'=>$secondaryPercentage);
}
private function _getAllPermutation($personality){
$combined = array($personality->typeA,$personality->typeB,$personality->typeC,$personality->typeD,$personality->typeE);
sort($combined);
$permutation = array();
for($i=0;$i<sizeof($combined);$i++){
for($j=$i+1;$j<5;$j++){
array_push($permutation,$combined[$i]."-".$combined[$j]);
}
}
return $permutation;
}

How to generate unique keys by concatenating user information in PHP CodeIgniter?

I want to create keys based on the information provided by the user. For example, if a user inserts their name, phone, country and some other information then my code should concatenate some fields and store a unique key into the same user table where I have field key. Example:
JACK-691-INDIA-10-001
So here, Jack would be the name inserted by user, 691 would be country code India is name of country, 10 is no of users and 001 is his database id.
In model I have a function get_new() where I initialize all the variables in array and I want to concatenate some variables and form a string(key) to be saved in key field.
The Model:
public function get_new(){
$user = new stdClass();
// $user->id = '';
$user->sip_username='';
$user->sip_password='';
$user->key='';
$user->allocation_block='';
$user->name='';
$user->email = '';
$user->password = '';
$user->phone='';
$user->user_num='';
$user->address = '';
$user->status = '';
$user->country='';
$user->created = '';
$user->modified = '';
$user->balance = '';
return $user;
$this->session->set_userdata($data);
}
The Controller Edit method :
public function edit ($id = NULL)
{
// Fetch a user or set a new one
if ($id) {
$this->data['user'] = $this->reseller_m->get($id);
count($this->data['user']) || $this->data['errors'][] = 'User could not be found';
}
else {
$this->data['user'] = $this->reseller_m->get_new();
}
// Set up the form
$rules = $this->reseller_m->rules_admin;
$id || $rules['password']['rules'] .= '|required';
$this->form_validation->set_rules($rules);
// Process the form
if ($this->form_validation->run() == TRUE) {
$data = $this->reseller_m->array_from_post(array('sip_username','sip_password','key','allocation_block','name','email','password','phone','balance','user_num','address','country','created','modified','status'));
$data['password'] = $this->reseller_m->hash($data['password']);
$key=$this->reseller_m->save($data, $id);
$this->db->insert_id();
/* $key=$this->reseller_m->save($data, $key);
$data['key'] =$this->reseller_m->insert_item($data['name'].$data['phone']);
*/
for($i=1; $i<=$data['user_num'];$i++)
{
$userdata=array('key'=>$key);
// here users is taken name of user table with retailer_id is field
$this->user_m->save($userdata,$id);
}
redirect('admin/reseller');
}
// Load the view
$this->data['subview'] = 'admin/reseller/edit';
$this->load->view('admin/_layout_main', $this->data);
}
Yes, you can pass the required values to the model, concatenate and create the string there, store it to database.
From the controller you can generate the key and then pass it to model :
$key = 'JACK-691-INDIA-10-001' // you have to concatenate the proper string, what is shown here is just as an example.
$this->load->model('users'); //the model in which the get_new function exsists
$this->users->get_new($key);
Model :
public function get_new($key) {
$user = new stdClass();
// $user->id = '';
$user->sip_username='';
$user->sip_password='';
$user->key='';
$user->allocation_block='';
$user->name='';
$user->email = '';
$user->password = '';
$user->phone='';
$user->user_num='';
$user->address = '';
$user->status = '';
$user->country='';
$user->created = '';
$user->modified = '';
$user->balance = '';
return $user;
$this->session->set_userdata($data);
}
why not,
sha256( serialize( $user ));
Not saying it's necessarily a good idea to do this, but.
You can use any hash functions to generate a unique hash for a given string.
Some Popular ones :
md5
sha1
You can use the hash() to try out various hash functions. Note than none of these are meant to be decrypted.

Categories