Laravel BD::rollBack Don't work in my code - database

I made the code below in order to validate a transaction in which the balance and history would be saved in the database or none of them. However, when I run the code and check the database I see that the balance is still being inserted into the bank instead of being canceled. What could be the mistake?
Below is the method code of my balance model responsible for the operation
public function deposit(float $value) : Array {
DB::beginTransaction();
$totalBefore = null;
// $totalBefore = $this->amount ? $this->amount : 0;
$this->amount += number_format($value, 2, ".", '');
$deposit = $this->save();
$historic = auth()->user()->historics()->create([
'type' => 'I',
'amount' => $value,
'total_before' => $totalBefore,
'total_after' => $this->amount,
'date' => date('Ymd'),
]);
if ($deposit && $historic) {
DB::commit();
return [
'success' => true,
'message' => 'Sucesso ao recarregar!'
];
}
else {
DB::rollBack();
return [
'success' => false,
'message' => 'Falha ao recarregar!'
];
}
}

When you use save() it is not getting rolled back by db::rollBack().

Related

How to match an input value in Laravel match before saving to sqlite database

I am trying to make the value of $input data to first match with one the pluck array values in a user table in the database before the input is saved and a response of 'its a match be given'. I trying to put these checks on an API I'm making. I'm new to laravel API and I will appreciate the help. Thank you
public function create(Request $request)
{
//
$this->validate($request, [
'inputed_number' => 'required|unique:users',
'user_id' => 'required'
]);
try {
Auth::user();
$phonenumber = new PhoneNumber();
$phonenumber->inputed_number = $request->inputed_number;
$phonenumber->user_id = $request->user_id;
if($this->user->phonenumber()->save($phoneuumber)){
$user = User::all();
$input = $request->only('inputed_number');
$user_number = $user->pluck('phone');
foreach ($input as $phone) {
if ($phone !== $user_number) {
return response()->json([
'success' => false,
'message' => 'Invalid number',
'data' => $phone,
], Response::HTTP_UNAUTHORIZED);
}
return response()->json([
'success' => true,
'message' => 'Its a match!!',
'data' => $phone,
]);
}
}
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => 'You have already inputted this number.',
], Response::HTTP_UNAUTHORIZED);
}
}
just get the whole user object with Auth:user no need for the pluck statement, you can access values directly via user object,
$user = Auth:user();
$input = $request->only('inputed_number');
if($user->phone !== $input ) {
//perform this code
}
If you want to match phone numbers from all users,
//get all users where phone number matches
$users = User::where('phone', $input)->get();
// iterate through $users rows
foreach ($users as $user) {
///do some thing
}

if the database is empty, code will not work

if the database does not contain an entry, the code will not work. If an entry exists, the code works. Does anyone know why the code only works if there is already an entry in the database?
I get the timeout error:
Maximum execution time of 30 seconds exceeded
_
with the code I create the user, then his profile in connection with the inviting URL. A unique code with a length of 7 characters is created, which is the individual invitation URL.
I need the loop because it has to be checked if the code has ever been generated. Or is there a better solution?
protected function create(array $data)
{
if($data['gender'])
{
$avatar = 'defaults\avatars\male.jpg';
}
else
{
$avatar = 'defaults\avatars\female.jpg';
}
if (array_key_exists('team_id', $data) && $data['team_id']){
$team = $data['team_id'];
}else{
$team = Null;
}
if (isset($data['invited_id']) && $data['invited_id']){
$invited_from = $data['invited_id'];
}else{
$invited_from = Null;
}
$user = User::create([
'name' => $data['name'],
'team_id' => $team,
'invited_from_id' => $invited_from,
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'birthday' => $data['birthday'],
'gender' => $data['gender'],
'slug' => str_slug($data['username']),
'avatar' => $avatar,
'active' => false,
'activation_token' => str_random(255)
]);
$user->profile()->save(new Profile());
while (true) {
$randomstring = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyz"), 0, 7);
if (Invite::where('url','!=', $randomstring)->exists()) {
Invite::create([
'user_id' => $user->id,
'url' => $randomstring
]);
break;
}
}
//store notify for user in database
$usern = User::find($invited_from);
if($usern) {
User::find($usern->id)->notify(new NotifyInvite($user));
}
return $user;
}
The problem is not with your database, the problem is that you never break out of your loop if the condition is not satisfied. So while(true) will run forever. You need to add a default case to your condition, which will exit the loop.

Codeigniter Insert Array to Database

I have created a form in Codeigniter with a phone number field that dynamically is duplicated using javascript. So basically I can have one or more fields like this.
<input name="phone[]" value=""type="text">
<input name="phone[]" value=""type="text">
Then in my controller I have
$form_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'phone' => $this->input->post('phone[]')
);
Then I am saving this to my dabase like so
function SaveForm($form_data)
{
$this->db->insert('customers', $form_data);
if ($this->db->affected_rows() == '1')
{
return TRUE;
}
return FALSE;
}
but obviously the code for 'phone' is wrong, I just cant figure out how to properly do this.
you can't save array in to database. You can convert it in to string using implode() and whenever you needed then convert it back in array using explode(). Like below
$phone=implode(',',$this->input->post('phone'));
$form_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'phone' => $phone
);
OR
You can convert it to json string and when you needed convert back to Array Like below:
$phone = json_encode($this->input->post('phone'));
Convert back to array
$phone = json_decode($phone, TRUE);
Modify your function as below and it will works like charm,
function SaveForm($form_data)
{
foreach ($form_data as $contact)
{
$data[] = array(
'first_name' => $contact['first_name'],
'last_name' => $contact['last_name'],
'phone' => $contact['phone']
);
}
$this->db->insert_batch('customers', $data);
if ($this->db->affected_rows() > 0)
{
return TRUE;
}
return FALSE;
}
Modified:
Oh, yes you have to edit para array that you passed to SaveForm function.
Please use following code, ignore above code:
foreach($_POST['first_name'] as $key=>$fname)
{
$form_data[] = array(
'first_name' => $_POST['first_name'][$key],
'last_name' => $_POST['last_name'][$key],
'phone' => $_POST['phone'][$key],
);
}
function SaveForm($form_data)
{
$this->db->insert_batch('customers', $data);
if ($this->db->affected_rows() > 0)
{
return TRUE;
}
return FALSE;
}
In controller
$phone = $_POST['phone'];//this will store data as array. Check image 02
$form_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'phone' => $phone,//some times it works with '$phone'
);
In Model
function SaveForm($form_data)
{
$this->db->insert('customers', $form_data);
if ($this->db->affected_rows() == '1')
{
return TRUE;
}
else
{
return FALSE;
}
}
Tested
Image 01 (My form)
Image 02 (After Submitted)
mysql doesn’t has any array data type. So we can not store array directly into mysql database.
To do this we have to first convert array into string using php serialize() function then save it into mysql database.
for eg:php code to store array in database
$array = array("foo", "bar", "hello", "world");
$conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db("mysql_db",$conn);
$array_string=mysql_escape_string(serialize($array));
To retrieve array from database
$conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db("mysql_db",$conn);
$q=mysql_query("select column from table",$conn);
while($rs=mysql_fetch_assoc($q))
{
$array= unserialize($rs['column']);
print_r($array);
}
for array insertion to database use this programme in codeigniter controller=>
$inputdata=$this->input->post();
$phone=array($inputdata['phone']);
foreach($phone as $arr)
{
$phoneNo=$arr;
$f=count($phoneNo);
for($i=0;$i<$f;$i++)
{
$arre=[
'phone'=>$phoneNo[$i],
];
$insertB= $this->user_model->userdata($arre);
}
}
public function add_theme_pages(){
$page_name = $this->input->post('page');
$page_img = $this->input->post('page_img');
for($i=0; $i < count($page_name); $i++){
$pages_data = array(
'theme_id' => $this->input->post('theme_id'),
'theme_page_name' => $page_name[$i],
'theme_page_img' => $page_img[$i]
);
if($this->backendM->add_theme_pages($pages_data)){
$this->session->set_flashdata('message', 'Theme Added Successfully !');
$this->session->set_flashdata('message_class', 'green');
$this->create_template();
}else{
$this->create_template();
}
}
}

Js Helper submit issue on cakephp 2.x

I am using JS Helper submit in my cakephp 2.x version.
My code is fine as function is called.
<?php echo $this->Js->submit("Apply", array(
'div' => false,
'class' => 'general_button',
'style' => array('float:none;', 'margin: 10px;'),
'url' => array('controller' => 'poets', 'action' => 'index', 'field' => $search_term, 'value' => $search_value),
'update' => '#listID',
'confirm' => 'Are you sure you want to apply action to selected records ??',
'before' => "return isAnySelect(this.form);",
'success' => 'myShowMessage();')); ?>
Though function isAnySelect(this.form) is called but my function this.form returns undefined wats the issue with this code .. Please explain.
My function
function isAnySelect(frmObject) {
console.log(frmObject);
return false;
varAllId = "";
for (i = 1; i < frmObject.chkRecordId.length; i++) {
alert('Hiii');
alert(varAllId + "xs");
if (frmObject.chkRecordId[i].checked == true) {
if (varAllId == "") {
varAllId = frmObject.chkRecordId[i].value;
} else {
varAllId += "," + frmObject.chkRecordId[i].value;
}
}
}
if (varAllId == "") {
alert("Please select atleast one record !!");
return false;
} else {
document.getElementById('idList').value = varAllId;
return true;
}
}
Though function is called but it output undefined on console.

Drupal 7, Ubercart 3 Custom Checkout Pane $order not setting the variable

//create anew schedule pane at checkout
function uc_pizza_uc_checkout_pane() {
$panes[] = array(
'id' => 'schedule',
'callback' => 'uc_checkout_pane_schedule',
'title' => t('Pickup/Delivery Date & Time'),
'desc' => t("Show Pickup/Delivery Date & Time Pane"),
'weight' => 1,
'process' => TRUE,
'collapsible' => FALSE,
);
return $panes;
}
function uc_checkout_pane_schedule($op, $order, $form = NULL, &$form_state = NULL) {
require_once(drupal_get_path('module', 'uc_cart') . '/uc_cart_checkout_pane.inc');
switch($op) {
case 'view': //create a date-popup field and a separate field for time.
$format = 'Y-m-d';
if(isset($_REQUEST['panes']['schedule']['date']['date'])) {
$date = $_REQUEST['panes']['schedule']['date']['date'];
} else {
$date = date($format);
}
$descriptions = t("NOTE: You may schedule your pizza pickup or delivery below. The shop is only open from 5pm until 11pm, you may still place your order beyond store hours but it will be delivered the next working hour or your required schedule.");
$contents ['sched_date'] = array(
'#type' => 'date_popup',
'#title' => t('select a date'),
'#default_value' => $date,
'#date_format' => $format,
'#datepicker_options' => array('minDate' => 'today', 'maxDate' => variable_get("uc_pizza_max_days", '+6 days')),
'#date_label_position' => 'within',
'#date_increment' => 15,
'#date_year_range' => '-0:+0',
);
$base_hour= 5;
for($i=0; $i<25; $i++) {
$mins = str_pad((int) (($i % 4) * 15),2,"0",STR_PAD_LEFT);
$hour = str_pad((int) $base_hour,2,"0",STR_PAD_LEFT);
$options_time[$hour.$mins] = t($hour . ":" . $mins . " PM");
if($mins == 45) {
$base_hour++;
}
}
if(isset($_REQUEST['panes']['schedule']['time'])) {
$default_option = $_REQUEST['panes']['schedule']['time'];
} else {
$default_option = 0000;
}
$contents['sched_time'] = array(
'#type' => 'select',
'#title' => 'Time',
'#options' => $options_time,
'#default_value' => $default_option,
);
return array('description' => $descriptions, 'contents' => $contents);
break;
case 'prepare':
break;
case 'review': //**/THIS IS WHERE THE PROBLEM IS** please check process
dprint_r("order: ", $order); // only var with data
dprint_r("form: ", $form); //no data
dprint_r("form_state: ", $form_state); //no data
//$sched_date = $arg1->schedule_date;
//$sched_time = $arg1->schedule_time;
//$review[] = '<div class="giftwrap">' . t('You want #type as gift wrap medium', array('#type' => $gift_wrap_type)) . '</div>';
//$review[] = array('title' => t('Schedule'), 'data' => check_plain("$sched_date # $sched_time"));
//return $review;
break;
case 'process':
//here in process i put the var to $order->schedule_date but unable to see it in $order at view
$order->schedule_date = $form_state['panes']['schedule']['sched_date']['#value']['date'];
$order->schedule_time = $form_state['panes']['schedule']['sched_time']['#value'];
return TRUE;
break;
case 'settings':
$max_days = variable_get("uc_pizza_max_days", '+6 days');
variable_set("uc_pizza_max_days", $max_days);
$contents['max_days'] = array(
'#type' => 'textfield',
'#title' => t('Calendar Max Days Limit'),
'#default_value' => $max_days,
'#maxlength' => 60,
'#size' => 32,
);
return $contents;
break;
}
}
I'm trying to add a pane to checkout process of ubercart,
$op = view and settings works perfect.
I have problem with review i tried setting the variable at $op=process but i cannot find it in $op=review
tried this in process
$order->schedule_date = $form_state['panes']['schedule']['sched_date']['#value']['date'];
$order->schedule_time = $form_state['panes']['schedule']['sched_time']['#value'];
but
in review it seems $order->schedule_date and $order->schedule_time is not in $order;
Can anyone help out what im missing please... this is in D7
Use $order->data instead of trying to apply your custom settings directly to $order.
Try this under 'process'
case 'process':
// display arrays for devel testing
dpm($form);
dpm($order);
// use $order->data to store your submission data
$order->data['schedule_time'] = $form['panes']['schedule']['sched_time']['#value'];
break;
Then use $order under 'review' to get the data you need.

Resources