How to pass zero if input text is blank? - codeigniter

I am getting a bit issue with my calculation, when I pass Discount and Debit values it is doing its job, but when Values of Discount and Debit is nothing it returns a blank page. Here is my Model.. CODEIGNITER.
function createInvoice() {
$this->load->helper('date');
$date = date('Y-m-d H:i:s');
$data = array(
'Date' => $date,
'Terms_Of_Payment' => $this->input->post('termsOfPayment'),
'Sub_Total' => $this->input->post('subTotal'),
'Total' => $this->input->post('total') - $this->input->post('discount'),
'Discount' => $this->input->post('discount'),
'Debit' => $this->input->post('debit'),
'Payment_Cridet' => $this->input->post('total') - $this->input->post('debit') - $this->input->post('discount'),
'Note' => $this->input->post('note'),
'Customer_ID' => $this->input->post('customerId'),
'User_ID' => $this->session->userdata('id'));
$this->db->insert('invoice', $data);
return ($this->db->affected_rows() != 1) ? false : true;
}

The best way is to use the ternary operator.
$subtotal = $this->input->post('subTotal') == "" ? 0 : $this->input->post('subTotal');
And if your php version is 7.0> then use
$subtotal = $this->input->post('subTotal') ?? 0;

Use ternary operator at data array when assinging the value of debit and discount.Code is looks like as below:
function createInvoice() {
$this->load->helper('date');
$date = date('Y-m-d H:i:s');
$data = array(
'Date' => $date,
'Terms_Of_Payment' => $this->input->post('termsOfPayment'),
'Sub_Total' => $this->input->post('subTotal'),
'Total' => $this->input->post('total') - isset($this->input->post('discount'))?$this->input->post('discount'):0,
'Discount' => isset($this->input->post('discount'))?$this->input->post('discount'):0',
'Debit' => isset($this->input->post('debit'))?$this->input->post('debit'):0,
'Payment_Cridet' => $this->input->post('total') - isset($this->input->post('debit'))?$this->input->post('debit'):0 - isset($this->input->post('discount'))?$this->input->post('discount'):0',
'Note' => $this->input->post('note'),
'Customer_ID' => $this->input->post('customerId'),
'User_ID' => $this->session->userdata('id'));
$this->db->insert('invoice', $data);
return ($this->db->affected_rows() != 1) ? false : true;
}

Ternary operator logic is the process of using (condition) ? (true return value) : (false return value) statements to shorten your if/else structures.
So, you can use ternary operator login for pass zero if input text is blank.
Now, some change in your createInvoice() function like me :
$subTotal = $this->input->post('subTotal') == "" ? 0 : $this->input->post('subTotal');
$total = $this->input->post('total') == "" ? 0 : $this->input->post('total');
$discount = $this->input->post('discount') == "" ? 0 : $this->input->post('discount');
$debit = $this->input->post('debit') == "" ? 0 : $this->input->post('debit');
$data = array(
'Date' => $date,
'Terms_Of_Payment' => $this->input->post('termsOfPayment'),
'Sub_Total' => $subTotal,
'Total' => ($total - $discount),
'Discount' => $discount,
'Debit' => $debit,
'Payment_Cridet' => $total - $debit - $discount,
'Note' => $this->input->post('note'),
'Customer_ID' => $this->input->post('customerId'),
'User_ID' => $this->session->userdata('id')
);

Related

Undefinde offset:1 when importing laravel excel

this my code cause the trouble,
$cust = Customer::where('name', '=', $data[$i][0]['customer_name'])
->pluck('customer_id')[0];
this one for get customer id when i do store to sales order
$sales = array(
'customer_id' => Customer::where('name', '=', $data[$i][0]['customer_name'])->pluck('customer_id')[0],
'logistics_id' => Logistic::where('logistics_name', '=', $data[$i][0]['logistics'])->pluck('logistics_id')[0],
'subtotal' => $data[$i][0]['subtotal_rp'],
'shipping_cost' => $data[$i][0]['shipping_cost_rp'],
'discount_code' => 0,
'date_of_sales' => $data[$i][0]['date'],
'grand_total' => $data[$i][0]['grand_total_rp'],
'tax' => $data[$i][0]['tax_rp'],
'status' => $data[$i][0]['status'],
'discount_amount' => $data[$i][0]['discount_amount_rp']
);
$store_so = SalesOrder::create($sales);
but, when i do dd(), i get the right data
First of all, you need to check if the $data variable returns the data as you expect.
dd($data);
Next, you need to check that the $data array has the number of elements according to $total_data.
dd(count($data) == $total_data));
So basically, you just need to give condition or try-catch (recommended) :
if (isset($data[$i][0])) {
$customer = Customer::where('name', $data[$i][0]['customer_name'])->first();
$logistic = Logistic::where('logistics_name', $data[$i][0]['logistics'])->first();
if(!$customer){
dd('No customer found!');
}
if(!$logistic){
dd('No logistic found!');
}
$sales = [
'customer_id' => $customer->customer_id,
'logistics_id' => $logistic->logistics_id,
'subtotal' => $data[$i][0]['subtotal_rp'],
'shipping_cost' => $data[$i][0]['shipping_cost_rp'],
'discount_code' => 0,
'date_of_sales' => $data[$i][0]['date'],
'grand_total' => $data[$i][0]['grand_total_rp'],
'tax' => $data[$i][0]['tax_rp'],
'status' => $data[$i][0]['status'],
'discount_amount' => $data[$i][0]['discount_amount_rp'],
];
$store_so = SalesOrder::create($sales);
}
else{
dd('No $data[$i][0] found!');
}
PS : I recommend using the first() method instead of pluck('customer_id')[0].
It seems you need to get a customer_id from a customer_name.
Try to make everything simple:
$sales = array(
'customer_id' => Customer::where('name', $data[$i][0]['customer_name'])->first()->id,
...
);

because it shows Undefined offset: 0, seeder laravel?

I have the following for in which I create the records
foreach ($v as $k => $f){
if($v[$k] != false && $f['zip_code'] !=''){
$state = State::whereCode($f['code'])->get();
var_dump($state[0]->id);
\App\Models\ZipCodes::create([
'uuid' => Uuid::generate(4)->string,
'zip_code' => $f['zip_code'],
'city' => $f['city'],
'county' => $f['county'],
'state_id' => $state[0]->id,
]);
}
}
I have noticed that the error appears in the field 'state_id' => $ state [0] -> id
since if I comment and delete it from the table it doesn't give me the error.
In fact if I just leave
foreach ($v as $k => $f){
if($v[$k] != false && $f['zip_code'] !=''){
$state = State::whereCode($f['code'])->get();
var_dump($state[0]->id);
}
}
The same generates the error.

Coinpayment Laravel integration. Division by zero Exception

I am trying to integrate coinpayment. By using this - https://github.com/hexters/CoinPayment
But I got error says:
exception: "ErrorException"
file: "C:\xampp\htdocs\coinpayment\vendor\hexters\coinpayment\src\Http\Controllers\CoinPaymentController.php"
line: 45
message: "Division by zero"
Please Refer to author new commits in the git repository as he updated the package https://github.com/hexters/CoinPayment/commit/cf7de99e18948fe385e75dfa8ded0fb378c33ad4
In case the link is not working then go to your app route and then to vendor folder and follow path vendor/hexters/coinpayment/src/Http/Controllers and update CoinPaymentController.php file's public function ajax_rates() function with the below given code
public function ajax_rates(Request $req, $usd){
$coins = [];
$aliases = [];
$rates = CoinPayment::api_call('rates', [
'accepted' => 1
])['result'];
$rateBtc = $rates['BTC']['rate_btc'];
$rateUsd = $rates[config('coinpayment.default_currency')]['rate_btc'];
$rateAmount = $rateUsd * $usd;
$fiat = [];
$coins_accept = [];
foreach($rates as $i => $coin){
if((FLOAT) $rates[$i]['rate_btc'] > 0) {
if((INT) $coin['is_fiat'] === 0){
$rate = ($rateAmount / $rates[$i]['rate_btc']);
$coins[] = [
'name' => $coin['name'],
'rate' => number_format($rate,8,'.',''),
'iso' => $i,
'icon' => 'https://www.coinpayments.net/images/coins/' . $i . '.png',
'selected' => $i == 'BTC' ? true : false,
'accepted' => $coin['accepted']
];
$aliases[$i] = $coin['name'];
}
if((INT) $coin['is_fiat'] === 0 && $coin['accepted'] == 1){
$rate = ($rateAmount / $rates[$i]['rate_btc']);
$coins_accept[] = [
'name' => $coin['name'],
'rate' => number_format($rate,8,'.',''),
'iso' => $i,
'icon' => 'https://www.coinpayments.net/images/coins/' . $i . '.png',
'selected' => $i == 'BTC' ? true : false,
'accepted' => $coin['accepted']
];
}
if((INT) $coin['is_fiat'] === 1){
$fiat[$i] = $coin;
}
}
}
return response()->json([
'coins' => $coins,
'coins_accept' => $coins_accept,
'aliases' => $aliases,
'fiats' =>$fiat
]);
}

Codeigniter update_batch--view, but not execute

I am using Codeigniter 3.x and want to see an update_batch query, but not run it, while I am debugging the code.
This works for an update_batch:
$this->db->update_batch("`" . $this->fullGamesTable . "`", $fullGames, 'gameid');
and updates the database, but I want to view the update and not actually do the update.
Thanks.
Can you do like this
$data = array(
array(
'opt_id' => $hoptid1,
'q_id' => $hid,
'opt_val' => $sin_yes,
'opt_crct' => $sin_yescrt,
'opt_mark' => '1'
),
array(
'opt_id' => $hoptid2,
'q_id' => $hid,
'opt_val' => $sin_no,
'opt_crct' => $sin_nocrt,
'opt_mark' => '1'
)
);
$this->db->update_batch('option', $data, 'opt_id');
Try this
public function update_batch()
{
$data = $this->db->select('id,description')->from('insert_batch')->group_by('url')->get()->result_array();
$batch_update = [];
foreach ($data as $key => $value) {
$value['description'] = 'description';
$batch_update[] = [
'id' =>$value['id'],
'description' => $value['description']
];
}
echo "<pre>"; print_r($batch_update);
$this->db->update_batch('insert_batch',$batch_update,'id');
}

Laravel 4 - Return the id of the current insert

I have the following query
public static function createConversation( $toUserId )
{
$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;
$results = DB::table('pm_conversations')->insert(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
return $results;
}
How would i return the id of the row just inserted?
Cheers,
Instead of doing a raw query, why not create a model...
Call it Conversation, or whatever...
And then you can just do....
$result = Conversation::create(array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now ))->id;
Which will return an id...
Or if you're using Laravel 4, you can use the insertGetId method...In Laravel 3 its insert_get_id() I believe
$results = DB::table('pm_conversations')->insertGetId(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
This method requires that the id of the table be auto-incrementing, so watch out for that...
The last method, is that you can just return the last inserted mysql object....
Like so...
$result = DB::connection('mysql')->pdo->lastInsertId();
So if you choose that last road...
It'll go...
public static function createConversation( $toUserId )
{
$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;
$results = DB::table('pm_conversations')->insert(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
$theid= DB::connection('mysql')->pdo->lastInsertId();
return $theid;
}
I would personally choose the first method of creating an actual model. That way you can actually have objects of the item in question.
Then instead of creating a model and just save()....you calll YourModel::create() and that will return the id of the latest model creation
You can use DB::getPdo()->lastInsertId().
Using Eloquent you can do:
$new = Conversation();
$new->currentId = $currentId;
$new->toUserId = $toUserId;
$new->ip = Request::getClientIp();
$new->time = $now;
$new->save();
$the_id = $new->id; //the id of created row
The way I made it work was I ran an insert statement, then I returned the inserted row ID (This is from a self-learning project to for invoicing):
WorkOrder::create(array(
'cust_id' => $c_id,
'date' => Input::get('date'),
'invoice' => Input::get('invoice'),
'qty' => Input::get('qty'),
'description' => Input::get('description'),
'unit_price' => Input::get('unit_price'),
'line_total' => Input::get('line_total'),
'notes' => Input::get('notes'),
'total' => Input::get('total')
));
$w_id = WorkOrder::where('cust_id', '=', $c_id)->pluck('w_order_id');
return $w_id;

Resources