check query no result in laravel 5.5 - php

I would like to find a way to check if my query result doesn't return a value. Example:
If in my tableExample on database there isn' t the id that I'm passing , the method should return an exception or a simple echo that indicate me the not presence in the table
My code below:
try{
DB::table('tableExample')
->where('id', "2")
->update(['update' => "1"]);
return $result= array("result" => "true" );
}catch(QueryException $e){
return $result= array("result" => "false" );
echo " - ".$e;
}
}

update method return integer value (affected rows) if success, try like this
try{
$update = DB::table('tableExample')
->where('id', "2")
->update(['update' => "1"]);
if($update){
$result = array("result" => true );
}else{
$result = array("result" => false,"message"=>"Not Found" );
}
}catch(QueryException $e){
$result = array("result" => false,"message"=>$e->getMessage() );
}
return $result;

Use findOrFail() helper method. That way you do not need to wrap the action in a try catch since if findOrFail does not find the row then it will throw an exception.
$resultData = DB::table('tableExample')->findOrFail(2);
$update = $resultData->update(['update' => "1"]);
if(!$update){
return response(['results'=>false]);
}
return response(['results'=> true]);
}
update() method returns a boolean true for success on update and versa.

You can do this by using the whereExists clause:
https://laravel.com/docs/5.5/queries#where-exists-clauses
https://laravel.com/api/5.5/Illuminate/Database/Query/Builder.html#method_exists

Related

Cannot access offset of type string on string while trying to access an array in an object in laravel controller

i am a bit confused as i have tried what i understand about fetching an item in an array in an object .
let me break down
in my client endpoint
$client=Client::where('id',$client)->firstOrFail();
$arr = json_decode($client->attributes);
return response()->json($arr);
when i return like this
return response()->json($client->attributes);
i get
{
"full_details_acknowledgement": "10",
"offer_letter_acknowledgement": "10",
"offer_letter": "10",
"offer_letter_variables": [
"basic_salary",
"housing_allowance",
"transport_allowance",
"meal",
"entertainment",
"hazard_allowance",
"leave_allowance",
"utility",
"monthly_gross_salary",
"statutory_deductions",
"employee_pension",
"payee_tax",
"total_deductions",
"net_monthly_salary",
"austin"
],
"company": "global-manpower"
}
i am trying to get the values of offer_letter_variables and safe them in a variable
like this , this is also what i have tried
foreach ($client->attributes['offer_letters_variables'] as $variable){
$offer_letters_variables->put($variable,isset($request->{$variable}) ? $request->{$variable} : 0 );
}
but if i try it as the above i have the error
"message": "Cannot access offset of type string on string"
heres a full view of my code(i commented out some parts)
public function submitSingleUploadCandidates($client,Request $request){
$request->validate([
'job_role_id'=>'required',
'mail_template_id'=>'required',
'first_name'=>'required',
'last_name'=>'required',
'user_type'=>'required',
'email'=>'required',
]);
$job_level=JobLevel::find($request->job_level_id);
$job_role=JobRole::findOrFail($request->job_role_id);
$mail_template=MailTemplate::findOrFail($request->mail_template_id);
$client=Client::where('id',$client)->firstOrFail();
//return response()->json($client->attributes);
// $arr = json_decode($client->attributes);
//dd($client);
// return response()->json(gettype($arr));
// return response()->json($arr);
$offer_letters_variables=collect([]);
//return response()->json($offer_letters_variables);
// $var = $client->attributes[''];
// dd($var);
foreach ($client->attributes['offer_letters_variables'] as $variable){
$offer_letters_variables->put($variable,isset($request->{$variable}) ? $request->{$variable} : 0 );
}
$attr=collect(['offer_letter_variables'=>$offer_letters_variables]);
$user=User::where('email',$request->email)->first();
if ($user){
Session::flash('fail', 'Candidate with email already exist');
$payload=['status'=>'fail','details'=>'Candidate with email already exist'];
return response()->json($payload, 200);
return redirect()->back()->withInput();
}
$password=Str::random(7);
$job_level_id = $job_level->id ?? null;
$new_user=User::create([
'client_id'=>$client->id,
'email'=>$request->email,
'emp_num'=>$request->emp_num,
'first_name'=>$request->first_name,
'last_name'=>$request->last_name,
'stage_id'=>1,
'user_type'=>$request->user_type,
'job_level_id'=>$job_level_id,
'job_role_id'=>$job_role->id,
'attributes'=>$attr,
'password'=>Hash::make($password),
]);
// $mail_constants['MacTay Signature Banner'] = '';
$mail_constants = $this->getMailConstants($new_user);
$mail_constants['candidate_password']=$password;
$mail_constants['deadline']=Carbon::now()->addWeekdays(2)->format('D d M, Y');
$mail_constants['admin_name']=auth()->user()->name;
$mail_content=$this->convertMailTemplateToEmail($mail_template,$mail_constants);
$mail_template->subject = str_replace('{{job_role}}', $mail_constants['job_role'], $mail_template->subject);
$mail_template->subject = str_replace('{{client_name}}', $mail_constants['client_name'], $mail_template->subject);
Mail::to($new_user->email)->send(new AdminSendMail($mail_content,$mail_template->subject));
$message="Your account has been created on Mactay App. Email: {$new_user->email}, Temp Password: {$password}. URL: onboarding.mactay.com";
SendSMSJob::dispatch($new_user->phone,$message);
activity()->withProperties(['client_id' => $client->id])->log('Upload single candidate to '.$client->name);
Session::flash('success', 'Successfully Uploaded Single Candidates Details');
$payload=['status'=>'success','details'=>'Successfully Uploaded Single Candidates Details'];
return response()->json($payload, 200);
}
please what am i doing wrong, please help , thanks in advance
You forgot to json_decode $client->attributes
$clientAttributes = json_decode($client->attributes);
foreach ($clientAttributes->offer_letter_variables as $variable){
$offer_letters_variables->put(
$variable,
$request->{$variable} ?? 'not set'
);
}
$attr = collect(['offer_letter_variables' => $offer_letters_variables]);
if you want to access it like an array you can json_decode the value like as an associative array.
$clientAttributes = json_decode($client->attributes, true);
dd($clientAttributes['offer_letter_variables']);
Also not that you have misspelled offer_letter_variables as offer_letters_variables in you foreach loop.
You will get offer_letter_variables like this.
$offerLetters = 0;
$client=Client::where('id',$client)->firstOrFail();
if(isset($client->attributes['offer_letter_variables'])){
$offerLetters = $client->attributes['offer_letter_variables'];
}
do you need to use the second parameter of json_decode ? For remember, used if it's an associative array
$client=Client::where('id',$client)->firstOrFail();
$arr = json_decode($client->attributes);
What return gettype() ? Array ?
thanks to #maazin , the solution was to use json_decode $client->attributes and then use foreach like so
$clientAttributes = json_decode($client->attributes);
foreach ($clientAttributes->offer_letter_variables as $variable){
$offer_letters_variables->put(
$variable,
$request->{$variable} ?? 'not set'
);
}
$attr = collect(['offer_letter_variables' => $offer_letters_variables]);

zend update is deleting old values

I am doing update in zend which in some cases doesn't update all the fields, the fields that are not updated become null as if we are doing an add.
This is the code from the Controller
$result = $theuserModel->updateUserTest(
$id,
$this->getRequest()->getPost('user_name'),
/*some code*/
$this->getRequest()->getPost('user_postee')
);
if ($result) {
$this->view->notif = "Successfull Update";
return $this->_forward('index');
}
The corresponding model
public function updateUserRest($id, $nom,$poste)
{
$data = array(
'user_name' => $nom,
'user_postee' => $poste
);
$result=$this->update($data, 'user_id = '. (int)$id);
return $result;
}
I do an update for user_name only I found that the old value of user_postee got deleted and replaced by the default value (initial value which we get at the time of creation) for example null.
Thanks in advance!
I have done this changes (bad solution) If anyone has another one optimised
->Controller
if($this->getRequest()->getPost('user_name')){
$resultname=$userModel->updateUserName($id,$this-
>getRequest()->getPost('user_name'));
}
if($this->getRequest()->getPost('user_postee')){
$resultpostee=$userModel->updateUserPoste($id,$this-
>getRequest()->getPost('user_postee'));
}
if ($resultname|| $resultpostee){
$this->view->notif = "Mise à jour effectuée";
return $this->_forward('index');
}
-> Model
public function updateUserName($id, $name)
{
$data = array(
'user_name' => $name
);
$result=$this->update($data, 'user_id = '. (int)$id);
return $result;
}
public function updateUserPostee($id, $postee)
{
$data = array(
'user_postee' => $poste
);
$result=$this->update($data, 'user_id = '. (int)$id);
return $result;
}
that is complete correct response of update in Zend Db Table.
I believe your assumption is if the value of 'user_postee' is null then it should not be updated into the database, am I correct.
The answer is they will update the new value of "NULL" into the database.
To avoid it , what you should do is
using fetchrow() to get the value of the line by id
foreach user_name and user_postee check if the value of them matching the array value your fetched , if nothing changed or Null, then use the old value from array , if new value exist use new value insert into the array , finally use update to update the new array into database
Assume your Table Column is also "user_name" and "user_postee"
public function updateUserRest($id, $nom,$poste)
{
$row = $this->fetchRow('user_id = '. (int)$id);
if(!empty($nom) && $row['user_name'] != trim($nom)){
$row['user_name'] = $nom;
}
if(!empty($poste) && $row['user_poste'] != trim($poste)){
$row['user_poste'] = $poste;
}
$result=$this->update($row, 'user_id = '. (int)$id);
return $result;
}

Codeigniter get mysql value

Can someone please guide me how I can fetch mysql row's value for "pk" to the $response variable to be able to allow the script to unfollow users automatically. I have already tried the script and it does unfollow when an pk id is provided but I want to automatically fetch it from mysql to be able to run it. Thank you for any help provided.
These are the methods I tried with no success:
$this->db->select('pk');
$this->model->from(INSTAGRAM_FOLLOW_TB);
$this->db->where("id = '11'");
$query1 = $this->db->get();
$result = $query1->result();
Main ID that only unfollow this ID- created by Mushfik Media,
$response = $i->unfollow($result);
I have also tried
$accounts = $this->model->fetch("*", INSTAGRAM_ACCOUNT_TB, "id = '11'");
$response = $i->unfollow($accounts->pk);
But didn't work. $NEED MYSQL DATA VALUE is where the value is supposed to be echoed but doesn't
case 'unfollow':
try {
$result = $i->getSelfUsersFollowing();
if(!empty($result) && $result->status == "ok" && !empty($result->users)){
$response = $i->unfollow($NEED MYSQL DATA VALUE);
$response = $response->status;
$CI =& get_instance();
$CI->load->model('Schedule_model', 'schedule_model');
$lang = $CI->db->insert(INSTAGRAM_FOLLOW_TB, array(
"pk" => $row->pk,
"name" => $row->username,
"type" => $data->schedule_type,
"uid" => $data->uid,
"account_id" => $data->account,
"account_name" => $data->name,
"created" => NOW
));
}
} catch (Exception $e){
$response = $e->getMessage();
}
break;
Maybe something like this to get your pk:
$query1 = $this->db->select('pk')
->from(INSTAGRAM_FOLLOW_TB)
->where('id', 11)
->get();
if( $query1->num_rows() == 1 ){
$row = $query1->row();
$response = $i->unfollow( $row->pk );
}
Regarding your information that you are trying to use $this when not in object context, because you are in a helper, you need to get the CI super object. So, if you were trying to use $this->db, you would do this:
$CI =& get_instance();
// Now you can use $CI->db
// and anything you would normally
// access via $this in a controller
// or model
OK, finally to show an example of how to order or limit a query:
$query1 = $this->db->select('pk')
->from(INSTAGRAM_FOLLOW_TB)
->where('id', 11)
->order_by('your_timestamp_field', 'ASC') // This would order by timestamp in ascending order
->limit(1) // This would limit to a single row
->get();

how to retrieve last insert id in uuid codeigniter

i have a trouble when retrieve last insert id in codeigniter.
when i try to debug like var_dump();
the output just send int(0)
i use uuid as id with primary key. this is the code:
$this->db->set('id_customer','uuid_short()',FALSE);
$query = $this->db->insert('customer',$data);
$id = $this->db->insert_id();
echo var_dump($id);
if($query)
{
$array = array(
'kode_trans' => 'uuid()',
'trans_date' => 'NOW()'
);
$this->db->set('id_customer','$id');
$this->db->set($array,'',FALSE);
$this->db->insert('transaction_header');
return $id;
}else{
return FALSE;
}
im newbie in ci.
there is something wrong with my code?
The "insert_id" function uses PHP's mysql_insert_id function, which returns "The ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value"
You could try it this way;
$id = uuid_short();
$data['id_customer'] = $id;
$query = $this->db->insert('customer', $data);
if ( $query )
{
$array = array(
'kode_trans' => 'uuid()',
'trans_date' => 'NOW()'
);
$query = $this->db->insert('transaction_header', $array);
return $id;
}
else
{
return false;
}

Unable to catch Exception using code igniter

This is my controller code which save data in table but when I put more than max length column data , it is not retuning me STATUS false; nothing is happening. please help
function saveImproveUs(){
$status =array("STATUS"=>"false");
try{
$improveUs = array(
'NAME' => trim($this->input->post('name')),
'EMAIL' => trim($this->input->post('email')),
'LOCATION' => trim($this->input->post('location')),
'MESSAGE_TYPE' => trim($this->input->post('messageType')),
'COMMENTS' => trim($this->input->post('comments'))
);
// Save improve us
$this->db->insert('trn_improve_us', $improveUs);
if ($this->db->affected_rows() > 0){
$status = array("STATUS"=>"true");
}
}catch(Exception $ex) {
//show_error($ex);
echo "I am in exception";
exit;
}
echo json_encode (array($status)) ;
}
You have to throw the exception, it won't do this for you.
if ($this->db->affected_rows() > 0){
$status = array("STATUS"=>"true");
}
else {
throw new Exception("Could not insert data");
}
Also inserting more data than a column can hold will automatically get cut-off in MySQL, the insert won't actually fail. You should use strlen to check the length of a string and validate it manually.

Categories