Call to a member function addDays() on string - laravel-5

I'm trying to addDays to a date using Carbon with Laravel, but I don't get why I'm receiving this error. I have checked some posts in StackOverflow, but no one has helped me to solve it.
This is my code:
$user = Auth::user();
$orders = DB::table('orders')->where('user_id', Auth::user()->id)->get();
$totalValue = 0;
$percentage = 0;
$currentDate = $carbon->now();
$currentDate = Carbon::parse($currentDate)->format('d/m/Y');
//$percentage = ($order->price * 0.05) / 30;
foreach($orders as $order) {
$nextDate = Carbon::parse($order->created_at)->format('d/m/Y');
if(1 == 1) {
$nextDate->addDays(1);
DB::table('orders')->where('user_id', Auth::user()->id)->update(['profit' => $order->profit]);
}
The error:

Try to add a day before change date format like below.
Carbon::parse($currentDate)->addDays(1);
or
Carbon::parse($currentDate)->addDay();
The simple way to add a day from today date is Carbon::now()->addDay();
Thanks.

I guess you are not saving your created_at date properly. Try following code.
$user = Auth::user();
$orders = DB::table('orders')->where('user_id', Auth::user()->id)->get();
$totalValue = 0;
$percentage = 0;
$currentDate = $carbon->now();
$currentDate = Carbon::parse($currentDate)->format('d/m/Y');
//$percentage = ($order->price * 0.05) / 30;
foreach($orders as $order) {
$nextDate = \Carbon\Carbon::parse($orders[0]->created_at)->format('d/m/Y');
$new_date = \Carbon\Carbon::createFromFormat('d/m/Y',$nextDate)->addDays(1)->toDateString();
if(1 == 1) {
//$nextDate->addDays(1);
$new_next_date = date('d/m/Y',strtotime($new_date));
DB::table('orders')->where('user_id', Auth::user()->id)->update(['profit' => $order->profit]);
}

Related

I want to store 1 month order data in one the problem is try to change date in day after day but it is storing 1970 date

This is my controller. I want to store 1 month order data in one. The problem is try to change date in day after day but it is storing 1970 date.
public function orderdatastore(Request $request){
$userid = 'GWU458910';
$orderid = "ORD".rand(10,99).rand(25,35).rand(155,255);
$pid = $request->product_id;
// Fetch Product name ny Product id
$product_data = DB::table('products')->where('product_id',$pid)->first();
$product_name = $product_data->product_name;
$selling_price = $product_data->selling_price;
// Fetch user name by user id
$customer_data = DB::table('customer_registrations')->where('customer_id',$userid)->first();
$customer = $product_data->product_name;
$fdate=$request->start_date;
$tdate=$request->end_date;
$datetime1 = strtotime($fdate); // convert to timestamps
$datetime2 = strtotime($tdate); // convert to timestamps
$days = (int)(($datetime2 - $datetime1)/86400);
for ($i=0; $i <= $days ; $i++) {
$order = new Orders;
$order->order_id = $orderid;
$order->product_id = $request->product_id;
$order->mobile = $request->mobile;
$order->user_id = $request->userid;
$order->user_name = $customer;
$order->product_name = $product_name;
$order->product_quantity = $request->quantity;
if($i==0) {
$order->order_date = $fdate;
}else{
$mydate = $fdate;
$daystosum = '1';
$dd = (int)(date('d-m-Y', strtotime($mydate.' + '.$daystosum.' days')));
$d2 = date('Y-m-d', $dd);
$d3 = $d2;
$order->order_date = $d3;
}
$order->product_selling_price = $selling_price;
// $order->volume = $request->volume;
$order->order_start_date = $fdate;
$order->order_end_date = $tdate;
$order->payment_mode = $request->payment_mode;
$order->mobile = $request->mobile;
$order->save();
echo "All data Saved";
}
The problem in your existing code is this line:
$dd = (int)(date('d-m-Y', strtotime($mydate.' + '.$daystosum.' days')));
strtotime() will give you a Unix timestamp;
date('d-m-Y', $timestamp) will give you a string like 2022-07-13;
Casting that string to an int will give you 2022 (and this part is the problem, this makes no sense);
A timestamp represents "seconds since Jan 1, 1970". 2022 seconds after midnight on Jan 1, 1970 is ... Jan 1, 1970, so date('Y-m-d', $dd); will give you 1970-01-01;
Probably the simplest fix is to just change that line to:
$dd = strtotime($mydate.' + '.$daystosum.' days');
But you are using Laravel, and Laravel comes with Carbon, which is extremely useful when working with dates. Here's a version of your code using Carbon instead:
public function orderdatastore(Request $request) {
$userid = 'GWU458910';
$orderid = "ORD" . rand(10, 99) . rand(25, 35) . rand(155, 255);
$pid = $request->product_id;
// Fetch Product name ny Product id
$product_data = DB::table('products')->where('product_id', $pid)->first();
$product_name = $product_data->product_name;
$selling_price = $product_data->selling_price;
// Fetch user name by user id
$customer_data = DB::table('customer_registrations')->where('customer_id', $userid)->first();
$customer = $product_data->product_name;
// Use Carbon to parse your input dates
$fdate = Carbon\Carbon::parse($request->start_date);
$tdate = Carbon\Carbon::parse($request->end_date);
// Use Carbon to find the difference between start/end dates
$days = $tdate->diffInDays($fdate);
// Create a copy of the start date to use for order dates
$mydate = $fdate->copy();
for ($i = 0; $i <= $days; $i++) {
$order = new Orders;
$order->order_id = $orderid;
$order->product_id = $request->product_id;
$order->mobile = $request->mobile;
$order->user_id = $request->userid;
$order->user_name = $customer;
$order->product_name = $product_name;
$order->product_quantity = $request->quantity;
$order->order_date = $mydate;
// Increment order date
$mydate->addDay();
$order->product_selling_price = $selling_price;
// $order->volume = $request->volume;
$order->order_start_date = $fdate;
$order->order_end_date = $tdate;
$order->payment_mode = $request->payment_mode;
$order->mobile = $request->mobile;
$order->save();
echo "All data Saved";
}
}

issue with reduce time to open in laravel

I am making a report in which user can check due balance of them invoice day wise like between 1-30 days how many amount due. between 30-60 days how many amount due etc for that I have make below function.
I don't know how can I optimize this process time.
public function yajraAgingARSummaryByDueDate()
{
$customerData = GenerateInvoice::select('orders.customer_id','customers.first_name', 'customers.last_name','customers.terms','customers.account_id','customers.account_suffix','invoice.due_date','invoice.invoice_number')
->leftJoin('orders','orders.id','=','invoice.order_id')
->leftJoin('customers', 'customers.id', 'orders.customer_id')
->whereDate('invoice.due_date','<=',date('Y-m-d'))
->whereNotNull('orders.customer_id')
->where('invoice.is_invoice_paid','=','no')
->whereNull('invoice.deleted_at')
->groupBy('orders.customer_id')
->get();
$resultArr = [];
if(count($customerData))
{
foreach($customerData as $key => $row)
{
$current = 0;
$b_1_30 = 0;
$b_31_60 = 0;
$b_61_90 = 0;
$b_over_90 = 0;
$total_ar = 0;
$balance = 0;
$invoiceData = GenerateInvoice::select('invoice.id')
->leftJoin('orders','orders.id','=','invoice.order_id')
->where('orders.customer_id',$row['customer_id'])
->whereDate('invoice.due_date','<=',date('Y-m-d'))
->whereNotNull('orders.customer_id')
->whereNull('invoice.deleted_at')
->where('invoice.is_invoice_paid','=','no')
->get();
if(count($invoiceData))
{
foreach($invoiceData as $row1)
{
$data = GenerateInvoice::select(DB::raw("abs(DATEDIFF(STR_TO_DATE(due_date, '%Y-%m-%d'),CURDATE())) AS Days"),'orders.total_order_value','payments.payment_amount')
->selectRaw(' (select sum(auto_cash_distributions.payment_amount) from auto_cash_distributions where auto_cash_distributions.order_id = invoice.order_id and payment_amount is not null ) as acd_payament_amount ')
->leftJoin('orders','orders.id','=','invoice.order_id')
->leftJoin('payments','payments.order_id','=','orders.id')
->where('invoice.id',$row1['id'])
->whereNotNull('orders.customer_id')
->whereNull('invoice.deleted_at')
->whereNull('payments.deleted_at')
->where('invoice.is_invoice_paid','=','no')
// ->groupBy('payments.invoice_id')
->first();
$days = $data['Days'];
$acd_payament_amount = !(empty($data['acd_payament_amount'])) ? $data['acd_payament_amount'] : 0;
$payment_amount = $data['payment_amount'] + $acd_payament_amount;
$amount = $data['total_order_value'] - $payment_amount;
// H 30/12
$amount = $amount;
$balance =$balance + $amount;
$total_ar = $total_ar + $amount;
// $total_ar = $amount;
if($days>90)
{
$b_over_90 = $b_over_90 + $amount;
}
else if($days <=90 && $days>=61)
{
$b_61_90 = $b_61_90 + $amount;
}
else if($days <=60 && $days>=31)
{
$b_31_60 = $b_31_60 + $amount;
}
else if($days <=30 && $days>=1)
{
$b_1_30 = $b_1_30 + $amount;
}
else
{
$current = $current + $amount;
}
}
}
$resultArr[$key]['account_id'] = $row['account_id'];
$resultArr[$key]['account_suffix'] = $row['account_suffix'];
$resultArr[$key]['first_name'] = $row['first_name'];
$resultArr[$key]['terms'] = $row['terms'];
$resultArr[$key]['due_date'] = $row['due_date'];
$resultArr[$key]['invoice_number'] = $row['invoice_number'];
$resultArr[$key]['balance'] = number_format($balance,2,'.','');
$resultArr[$key]['current'] = number_format($current,2,'.','');
$resultArr[$key]['b_1_30'] = number_format($b_1_30,2,'.','');
$resultArr[$key]['b_31_60'] = number_format($b_31_60,2,'.','');
$resultArr[$key]['b_61_90'] = number_format($b_61_90,2,'.','');
$resultArr[$key]['b_over_90'] = number_format($b_over_90,2,'.','');
$resultArr[$key]['total_ar'] = number_format($total_ar,2,'.','');
}
}
return Datatables::of($resultArr)
->addColumn('due_date',function($sql){
return !empty($sql['due_date']) ? date(get_config('date_format'),strtotime($sql['due_date'])) : '';
})
->addIndexColumn()
->rawColumns(['due_date'])
->make(true);
}
but this code is taking to much time to open. can anybody help me to optimize this code?

model and controller query to merge timein and timeout with single row in codeigniter

Please teach me how can I achieve this(Codeigniter framework)
Please see images that I want to achieve thank you.
and I'm also new to codeigniter and want to understand the answer.
enter image description here
Here is my database:
enter image description here
model
public function get_attendance_employees() {
$sql = 'SELECT * FROM tbl_employee';
//$binds = array(1);
$query = $this->db->query($sql);
return $query;
}
public function attendance_first_in_check($userid,$attendance_date) {
$sql = "SELECT * FROM tbl_employee_time_log as time_log WHERE userid = ? and substring(time_log.time,1,10) = ? and type = 'timein' limit 1";
$binds = array($userid,$attendance_date);
$query = $this->db->query($sql,$binds);
return $query;
}
public function attendance_first_in($userid,$attendance_date) {
$sql = "SELECT * FROM tbl_employee_time_log as time_log WHERE userid = ? and substring(time_log.time,1,10) = ? and type = 'timein'";
$binds = array($userid,$attendance_date);
$query = $this->db->query($sql, $binds);
return $query->result();
}
public function attendance_first_out_check($userid,$attendance_date) {
$sql = "SELECT * FROM tbl_employee_time_log as time_log WHERE userid = ? and substring(time_log.time,1,10) = ? and type = 'timeout' order by id desc limit 1";
$binds = array($userid,$attendance_date);
$query = $this->db->query($sql, $binds);
return $query;
}
public function attendance_first_out($userid,$attendance_date) {
$sql = "SELECT * FROM tbl_employee_time_log as time_log WHERE userid = ? and substring(time_log.time,1,10) = ? and type = 'timeout' order by id desc limit 1";
$binds = array($userid,$attendance_date);
$query = $this->db->query($sql, $binds);
return $query->result();
}
controller
public function attendance_bio()
{
$session = $this->session->userdata('username');
if(!empty($session)){
$this->load->view("admin/timesheet/attendance_bio", $data);
} else {
redirect('admin/');
}
// Datatables Variables
$draw = intval($this->input->get("draw"));
$start = intval($this->input->get("start"));
$length = intval($this->input->get("length"));
$attendance_date2 = $this->input->get("attendance_date"); //string
//$ref_location_id = $this->input->get("location_id");
//$convert_atten = strtotime($attendance_date2); //int value
//$attendance_date = $convert_atten->format('m-d-Y');
$attendance_date = date("m-d-Y",strtotime($attendance_date2));
//$timein = $this->Bio_model->get_attendance_date();
//$timein = $this->Bio_model->get_attendance_timein($get_day);
//$timein = $this->Bio_model->get_all();
$employee = $this->Bio_model->get_attendance_employees();
$data = array();
//var_dump($attendance_date);
foreach($employee->result() as $r){
$check = $this->Bio_model->attendance_first_in_check($r->userid,$attendance_date);
if($check->num_rows() > 0){
// check clock in time
$first_in = $this->Bio_model->attendance_first_in($r->userid,$attendance_date);
//$first_in2 = $first_in[0]->time->format('m-d-Y');
// clock in
$clock_in = new DateTime(strtotime($first_in[0]->time));
//$clock_in2 = $clock_in->format('H:i');
$clock_in2 = date_format($clock_in->time, 'H:i');
//$clock_in2 = var_dump($clock_in);
} else {
$clock_in2 = '-';
$clock_in = '-';
}
$check_out = $this->Bio_model->attendance_first_out_check($r->userid,$attendance_date);
if($check_out->num_rows() == 1){
$first_out = $this->Bio_model->attendance_first_out($r->userid,$attendance_date);
//$first_out2 = $firs
$clock_out = new DateTime(strtotime($first_out[0]->time));
if ($first_out[0]->time!='') {
//$clock_out2 = $clock_out->format('H:i');
//$clock_out2 = date('H:i',$clock_out);
$clock_out2 = date_format($clock_out->time, 'H:i');
} else {
$clock_out2 = '-';
}
}else {
$clock_out2 = '-';
$clock_out = '-';
}
$data[] = array(
$r->userid,
$attendance_date,
$clock_in2,
$clock_out2,
);
}
$output = array(
"draw" => $draw,
"recordsTotal" => $employee->num_rows(),
"recordsFiltered" => $employee->num_rows(),
"data" => $data
);
echo json_encode($output);
exit();
}
Thank you for providing more information on the topic and the code you have attempted so far. I have supplied an algorithm which I believe will work for you.
Contoller:
<?php namespace App\Controllers;
use App\Models\EmployeeTimeLog;
class Home extends BaseController
{
public function index($employeeId)
{
// get all between dates
$emplyeeModel = new EmployeeTimeLog();
// get one week before today - for example
$startDate = date("Y-m-d", strtotime("-1 week"));
$endDate = date("Y-m-d");
// get clock-in and clock-out for employee between dates
$timeIn = $emplyeeModel->getTimeIn($employeeId, $startDate, $endDate)->getResult();
$timeOut = $emplyeeModel->getTimeOut($employeeId, $startDate, $endDate)->getResult();
$timeInIndex = 0;
$timeOutIndex = 0;
$output = [];
$nextDate = $startDate;
// loop through all the days between start and end date
while($nextDate < $endDate){
// get the lowest "timein" datetime which is the same date as the search date $nextDate
$nextTimeIn = NULL;
while($timeInIndex < count($timeIn) && date("Y-m-d", strtotime($timeIn[$timeInIndex]->Time)) == $nextDate){
if(is_null($nextTimeIn)){
$nextTimeIn = $timeIn[$timeInIndex];
}
$timeInIndex ++;
}
// get the highest "timeout" datetime which is the same day as the search date $nextDate
$nextTimeOut = NULL;
while($timeOutIndex < count($timeOut) && date("Y-m-d", strtotime($timeOut[$timeOutIndex]->Time)) == $nextDate){
$nextTimeOut = $timeOut[$timeOutIndex];
$timeOutIndex ++;
}
// enter into a 2 dimentional array with
// index 0 = timein
// index 1 = timeout
$output[] = [$nextTimeIn, $nextTimeOut];
// get the next date
$nextDate = date('Y-m-d', strtotime($nextDate. ' + 1 days'));
}
// return view with data
return view('welcome_message', ["output" => $output]);
}
}
Model:
<?php
namespace App\Models;
use CodeIgniter\Model;
class EmployeeTimeLog extends Model{
private $tableName = "tbl_employee_time_log";
public function __construct(){
$db = \Config\Database::connect();
$this->builder = $db->table($this->tableName);
}
private function timeData($employeeId, $startDate, $endDate){
// builder function DRY
$this->builder->where("EmployeeId", $employeeId);
$this->builder->where("Time >", $startDate);
$this->builder->where("Time <", $endDate);
$this->builder->orderBy("Time", "ASC");
}
public function getTimeIn($employeeId, $startDate, $endDate){
// call builder function and add timeIn to only get clock in times
$this->timeData($employeeId, $startDate, $endDate);
$this->builder->where("Type", "timein");
return $this->builder->get();
}
public function getTimeOut($employeeId, $startDate, $endDate){
// call builder function and add timeout to only get clock out times
$this->timeData($employeeId, $startDate, $endDate);
$this->builder->where("Type", "timeout");
return $this->builder->get();
}
}
?>
View:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Timesheets</title>
</head>
<body>
<h1>Timesheets</h1>
<?php
echo "<h1>Times</h1>";
foreach ($output as $times) {
echo "Time in: ";
if(!is_null($times[0])){
echo $times[0]->Time;
}else{
echo "-";
}
echo " Time out: ";
if(!is_null($times[1])){
echo $times[1]->Time;
}else{
echo "-";
}
echo "<br>";
}
?>
</body>
</html>
Output:
Database:
The whole algorithm works by searching through the date between the start and end date of the dates provided. You can then check any timein and timeout values which have the same date as the loop date. If a date cannot be found, the default is NULL which is replaced by "-" in the view.
The algorithm specifically gets the earliest timein and the latest timeout value for the employee. This means that if the employee clocks-in twice in one day the earliest date will be used and the opposite for clock-out.
This algorithm specifically works for one employee, but just use your select * employees and loop through instead of the employeeId on the controller. You may want to look in the documentation for the Query Builder in CodeIgniter it makes querying the database much easier, and will escape data to protect from SQL Injections etc.
It could be better to redesign your database table and check on insert rather than manipulate on select. Where you have one row for each day and the timein and timeout which represent the time. Something like this:
You can check to see if the date already exists, if so override the current value if needed. If the current date doesn't exist for that employee create a new record.
If you need any clarification, let me know,
Thanks,

Vue changing variable value on receiveing data from backend Laravel

i hope you are all doing ok.
I have a weird problem that i just can't find a way to solve and the worst part I don't even know how to start looking for this problem over the internet.
Here's the case:
I make a DB request with the code below in Laravel:
public function previsao(){
$dados = [];
$tempoEntrega = 0;
$tempoTroca = 0;
$sugestaoCompra = 0;
$frequencia = 0;
$qnt = 0;
$qntI = 0;
$qntR = 0;
$todosOsDados = $this->TecManutencaoEstoquePecaRegM
->join('tec_manutencao_pecas', 'tec_manutencao_estoque_peca_regs.pecaId', 'tec_manutencao_pecas.id')
->where('dataComp', '!=', null)
->get();
foreach ($todosOsDados as $todId) {
$toIds[] = $todId->pecaId;
}
$idsUnicos = array_unique($toIds);
foreach ($idsUnicos as $idu) {
$ids[] = $idu;
}
foreach ($ids as $id) {
$peca = $this->TecManutencaoPecasM
->select('peca')
->where('id', $id)
->first();
$entrega = $this->TecManutencaoEstoquePecaRegM
->join('tec_manutencao_pecas', 'tec_manutencao_estoque_peca_regs.pecaId', 'tec_manutencao_pecas.id')
->where('dataComp', '!=', null)
->where('pecaId', $id)
->where('mov', 'i')
->select('data', 'dataComp', 'qnt', 'est_min')
->get();
foreach ($entrega as $e) {
$tempoEntrega += (Carbon::parse($e->data)->diffInDays(Carbon::parse($e->dataComp)));
$estMin = $e->est_min;
$qntI += $e->qnt;
}
$qntRetirada = $this->TecManutencaoEstoquePecaRegM
->join('tec_manutencao_pecas', 'tec_manutencao_estoque_peca_regs.pecaId', 'tec_manutencao_pecas.id')
->where('dataComp', '!=', null)
->where('pecaId', $id)
->where('mov', 'r')
->select('qnt')
->get();
foreach ($qntRetirada as $qr) {
$qntR += $qr->qnt;
}
$qnt = $qntI - $qntR;
$uso = $this->TecManutencaoEstoquePecaRegM
->where('pecaId', $id)
->where('mov', 'r')
->select('data')
->get();
foreach ($uso as $u) {
$ultimaEntrega = $this->TecManutencaoEstoquePecaRegM
->join('tec_manutencao_pecas', 'tec_manutencao_estoque_peca_regs.pecaId', 'tec_manutencao_pecas.id')
->where('pecaId', $id)
->where('mov', 'i')
->where('data', '<=', $u->data)
->select('data')
->orderBy('data', 'DESC')
->first();
$tempoTroca += (Carbon::parse($u->data)->diffInDays(Carbon::parse($ultimaEntrega->data)));
$ultimaTroca = $u->data;
}
$frequencia = count($entrega);
$sugestaoCompra = round(($tempoTroca * ($tempoEntrega + $frequencia)) - ($qnt - $estMin));
$tempoTrocaMedio = count($uso) == 0 ? $tempoTroca : round($tempoTroca / count($uso));
$tempoAteEstminAcabar = $qnt * $tempoTrocaMedio;
$dataProxComp = $tempoAteEstminAcabar - round($tempoEntrega / count($entrega));
$diasTroca = $tempoTroca <= 0 ? round($tempoEntrega / count($entrega)) : $dataProxComp;
$dados[] = [
'id' => $id,
'peca' => $peca->peca,
'tempoEntrega' => $tempoEntrega <= 0 ? $tempoEntrega : round($tempoEntrega / count($entrega)),
'tempoTroca' => $tempoTroca <= 0 ? $tempoTroca : round($tempoTroca / count($uso)),
'qntProxComp' => $sugestaoCompra,
//'dataProxComp' => date('d/m/Y', strtotime($ultimaTroca.'+'.$diasTroca.' days')),
'dataProxComp' => $ultimaTroca == 0 || $ultimaTroca == null ?
date('d/m/Y', strtotime($ultimaEntrega->data.'+'.$diasTroca.' days')) :
date('d/m/Y', strtotime($ultimaTroca.'+'.$diasTroca.' days')),
'qnt' => $qnt,
'estMin' => $estMin
];
$tempoEntrega = 0;
$tempoTroca = 0;
$sugestaoCompra = 0;
$frequencia = 0;
$qnt = 0;
$qntI = 0;
$qntR = 0;
}
//dd($dados);
return $dados;
}
This code returns what I've expected:
Then a get this return with Vue like this:
methods: {
getPredictions(){
axios.get(this.rotagetprevisoes, this.dadosIniciais).then(res => {
this.dadosIniciais = res.data
console.log(res.data)
})
},
rowClass(filtered, type){
if (!filtered) return
if (filtered.estMin < filtered.qnt) return 'table-success'
if (filtered.estMin = filtered.qnt) return 'table-warning'
if (filtered.estMin > filtered.qnt) return 'table-danger'
},
openRepModal(){
this.$root.$emit('bv::show::modal', 'gerRelPrev', '#btnShow')
},
sugModal(item){
if(item.qntProxComp >= 0){
this.qntSuges = item.qntProxComp
this.acimaEstMin = 'n'
} else {
this.qntSuges = Math.abs(item.qntProxComp)
this.acimaEstMin = 's'
}
this.dataSuges = item.dataProxComp
this.$root.$emit('bv::show::modal', 'adminSugestao', '#btnShow')
}
},
But what I got here is:
Note that the "estMin" has different values when is sent and when is received, the weirdest part is that it only goes from Laravel to Vue, nothing in the middle.
I already try changing a lot of parts of my code, doing it all over again but, ended up with the same result, try searching for something related over the internet but no succeed.
This field "estMin" is the only one affected and, it's not even a calculated field, it's only the data that I get from DB.
I simply don't understand why "estMin" comes from Laravel with the values that I expect and arrive in Vue with a different value.
One more thing, this is an array of objects, only pick one example to show you guys.
Can someone help me please?
thanks for trying to help me, i just figure what I was doing wrong and, it was stupid.
I've edited the question so you guys can have a better understand:
In the rowClass method, I have this line:
if (filtered.estMin = filtered.qnt) return 'table-warning'
I didn't notice the '=' sign, that's why the estMin was aways with a different value so, I change the '=' sign for '===' and the problems were solved:
if (filtered.estMin === filtered.qnt) return 'table-warning'
Honestly, I don't understand why exactly this method can be interfering with the other but, it is working.
Again, thank you all that have tried to help me.

How to get Select max value in codeigniter

Controller:
$next_id = $this->o->next_id();
$data['next_id']=$next_id;
Model:
public function next_id(){
$this->db->select_max('p_ori_id');
$max = $this->db->get('orientation_master');
if($max==0){
$next_id = 1;
}else{
$next_id = 1+$max;
}
return $next_id;
}
Return Error:
Object of class CI_DB_mysqli_result could not be converted to int
Please solve problem..
No offense to #pradeep but you may have some unexpected results if you don't have any rows. I suggest:
public function next_id()
{
$this->db->select_max('p_ori_id', 'max');
$query = $this->db->get('orientation_master');
if ($query->num_rows() == 0) {
return 1;
}
$max = $query->row()->max;
return $max == 0 ? 1 : $max + 1;
}
Hope this will help you:
public function next_id()
{
$this->db->select_max('p_ori_id', 'max');
$query = $this->db->get('orientation_master');
// Produces: SELECT MAX(p_ori_id) as max FROM orientation_master
$max = $query->row()->max;
if($max == 0){
$next_id = 1;
}else{
$next_id = $max+1;
}
return $next_id;
}
For more : https://www.codeigniter.com/user_guide/database/query_builder.html
You are getting that error becuase $max is a result set object and not an integer record value like you're trying to use it.
You can try this function to get the next id.
Modified function:
public function next_id(){
$this->db->select_max('p_ori_id', 'max');
$result = $this->db->get('orientation_master');
$row = $result->row_array();
$next_id = isset($row['max']) ? ($row['max']+1) : 1;
return $next_id;
}
If the column is auto increment, you can use the below code instead.
Alternative:
public function next_id() {
$sql_string = "SELECT `auto_increment` FROM INFORMATION_SCHEMA.TABLES WHERE table_name = '".$this->db->dbprefix."orientation_master'";
$query = $this->db->query($sql_string);
$row = $query->row_array();
return $row['auto_increment'];
}

Resources