What is better way instead of use GOTO in Laravel - laravel

Now I have to use GOTO for some logic in Laravel 5.6v.
How can I make code that works the same as GOTO and more beautiful code? :)
public function job_finished_search(Request $request)
{
$rFrom = $request->input('datepicker_from');
$rTo = $request->input('datepicker_to');
$rName =$request->customer_name;
if($rFrom == null){
if($rTo == null){
if($rName == null){
Flash::error('Search result not found');
return redirect(route('pdf.index'));
}
$query = Job::onlyTrashed()
->where('is_trash', 0)
->where('customer_name', $rName)
->orderBy('created_at', 'desc');
goto A;
}
elseif($rTo != null){
if($rName == null){
$query = Job::onlyTrashed()
->where('is_trash', 0)
->where('created_at', '<=', Carbon::parse($rTo)->endOfDay())
->orderBy('created_at', 'desc');
goto A;
}
...
...
}
A: $job_ids = $query->pluck('id')->all();

A Lot more cleaner way,
$buildquery=Job::onlyTrashed()->where('is_trash', 0);
if($request->filled('customer_name')){
$buildquery->where('customer_name', $request->customer_name);
}
if($request->filled('datepicker_to')){
$buildquery->where('created_at', '<=', Carbon::parse($request->datepicker_to)->endOfDay());
}
$result = $buildquery->orderBy('created_at', 'desc')->get();
$job_ids = $result->pluck('id');
you are not using $rFrom, anywhere so i omitted it.

Related

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 add another array value in codeigniter using getRecords

The orignial code was like this , I want to get landline_no value also in getRecords, How to do that
public function checklead() {
$lead = $_POST['number'];
$check = $this->common_model->getRecords('leads',array("phone_no"=>$lead));
if(count($check) > 0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$lead));
if($lead->assignto_self != 0) {
$assignto = $lead->assignto_self;
$key = 'Self Assign';
} else if($lead->assignto_se != 0) {
$assignto = $lead->assignto_se;
$key = '';}
What I have achieved so far,but not getting array values from getRecords
$lead = $_POST['number'];
$check = $this->common_model->getRecords('leads',array("phone_no"=>$lead),array("landline_no"=>$lead));
//echo "<pre>";
//print_r($check);
//echo $check[0]['landline_no'];exit;
if(count($check) > 0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$lead,"landline_no"=>$check[0]['landline_no']));
Code for getRecords:
function getRecords($table,$db = array(),$select = "*",$ordercol = '',$group = '',$start='',$limit=''){
$this->db->select($select);
if(!empty($ordercol)){
$this->db->order_by($ordercol);
}
if($limit != '' && $start !=''){
$this->db->limit($limit,$start);
}
if($group != ''){
$this->db->group_by($group);
}
$q=$this->db->get_where($table, $db);
return $q->result_array();
}
// Get Recored row
public function getRecored_row($table,$where)
{
$q = $this->db->where($where)
->select('*')
->get($table);
return $q->row();
}
Check my answer: This code also working well, i have written, but i am not sure , this logic is correct or not kindly check this one.
public function checklead() {
$lead = $_POST['number'];
if($this->common_model->getRecords('leads',array("phone_no"=>$lead)))
{
$check=$this->common_model->getRecords('leads',array("phone_no"=>$lead));
}
else
{
$check=$this->common_model->getRecords('leads',array("landline_no"=>$lead));
}
echo "<pre>";
//echo $check;
//print_r($check); exit;
$p= $check[0]['phone_no'];
$l= $check[0]['landline_no'];
// exit;
if(count($p) > 0 || count($l)>0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$p));
$lead1 = $this->common_model->getRecored_row('leads',array("landline_no"=>$l));
if($lead->assignto_self != 0 || $lead1->assignto_self != 0) {
$assignto = $lead->assignto_self;
$key = 'Self Assign';
} else if($lead->assignto_se != 0 || $lead1->assignto_se != 0) {
$assignto = $lead->assignto_se;
$key = '';
}else if($lead->assignto_tl != 0 || $lead1->assignto_tl != 0) {
$assignto = $lead->assignto_tl;
$key = '';
} else if($lead->uploaded_by != 0 || $lead1->uploaded_by != 0) {
$assignto = $lead->uploaded_by;
$key = 'Uploaded by';
}
$user = $this->common_model->getRecored_row('admin',array("id"=>$assignto));
$role = $this->common_model->getRecored_row('role',array("id"=>$user->role));
$this->session->set_flashdata('message', array('message' => 'This Lead Already exist with '.$user->name.' ('.$role->role.') '.' ','class' => 'danger'));
redirect(base_url().'leads');
} else {
redirect(base_url().'leads/add_newlead/'.$lead);
}
}
There does not seem to be any reason to use getRecords(). The $check value has no useful purpose and creating it is a waste of resources.
We don't need $check because getRecord_row() will return the "lead" if found so the only check needed is to see if getRecord_row() returns anything. getRecord_row() uses the database function row() which returns only one row or null if no rows are found. Read about row() here.
If what you want is to find the "lead" that has either a "phone_no" or a "landline_no" equal to $_POST['number'] then you need to use a custom string for the where clause. (See #4 at on this documentation page.) You need a custom string because getRecord_row() does not allow any other way to ask for rows where a='foo' OR b='foo'. Here is what I think you are looking for.
public function checklead()
{
// use input->post() it is the safe way to get data from $_POST
$phone = $this->input->post('number');
// $phone could be null if $_POST['number'] is not set
if($phone)
{
$lead = $this->common_model->getRecored_row('leads', "phone_no = $phone OR landline_no = $phone");
// $lead could be null if nothing matches where condition
if($lead)
{
if($lead->assignto_self != 0)
{
$assignto = $lead->assignto_self;
$key = 'Self Assign';
}
else if($lead->assignto_se != 0)
{
$assignto = $lead->assignto_se;
$key = '';
}
}
}
}
The main difference between getRecords() and getRecord_row() is the number of records (rows of data) to return. getRecord_row() will return a maximum of one record while getRecords() might return many records.
getRecords() accepts arguments that allow control of what data is selected ($db, $select), how it is arranged ($ordercol, $group), and the number of rows to retrieve ($limit) starting at row number x ($start) .

How to write a condition based query?

I have a query to run based on the user type selected. I have around 9 users. Based on 9 users, only first line will be different remaining conditions are going to be same.
Below is the code I am writing. I dont want to repeat the same line again for 9 users.
How can I this query without repeating the condition?
if($user_id == 1) {
$slmids = Production::groupBy('gid', 'rid', 'aid', 'sid')
//same
->where("yrsno", $currentYear)
->orderBy("order")
->orderBy("rid")
->orderBy("aid")
->get(['gid', 'rid', 'aid', 'sid'])
->toArray();
}
else if($user_id == 2) {
$slmids = Production::where('gid', $user['sgrp'])
//same
->where("yrsno", $currentYear)
->orderBy("order")
->orderBy("rid")
->orderBy("aid")
->get(['gid', 'rid', 'aid', 'sid'])
->toArray();
}
else if($user_id == 3){
.....
}
$production = Production::where("yrsno", $currentYear)
->orderBy("order")
->orderBy("rid")
->orderBy("aid")
->get(['gid', 'rid', 'aid', 'sid']);
if ($user_id == 1) {
$production = $production->groupBy('gid', 'rid', 'aid', 'sid');
} else if($user_id == 2) {
$production = $production->where('gid', $user['sgrp']);
} else if($user_id == 3) {
....
}
$result = $production->toArray();
You can try like this way.
$slmids = Production::where("yrsno", $currentYear);
if ($user_id == 1)
$slmids = $slimds->groupBy('gid', 'rid', 'aid', 'sid');
elseif ($user_id == 2)
$slmids = $slmids->where('gid', $user['sgrp']);
...
// you can use switch-case if you want
$slmids = $slmids->orderBy('order')
->orderBy('rid')
->orderBy('aid')
->get(['gid', 'rid', 'aid', 'sid'])
->toArray();
I believe groupBy must be placed first before orderBy
Use When to make easy Try following code:
$production = Production::where("yrsno", $currentYear)
->orderBy("order")
->orderBy("rid")
->orderBy("aid")
->query();
$production->when($user_id == 1, function ($query) {
$query->groupBy('gid', 'rid', 'aid', 'sid');
});
$production->when($user_id == 2, function ($query) use ($user) {
$query->where('gid', $user['sgrp']);
});
$results = $production->get()->toArray();
check more example https://stackoverflow.com/a/52333718/8970463

Filtering Eloquent Collection

Trying to filter a collection object down based upon any combination of multiple values. This is as far as I've got. Not happening. Any clues for me?
public function search()
{
$posts = Posting::all();
$type_id = Input::get('type_id');
$country_id = Input::get('country_id');
$province_id = Input::get('province_id');
$posts = $posts->filter(function($post)
{
if( !empty($type_id) && $type_id>0 )
{
return $post->where('type_id','=',$type_id);
}
})->values();
$posts = $posts->filter(function($post)
{
if( !empty($country_id) && $country_id>0 )
{
return $post->where('country_id','=',$country_id);
}
})->values();
$posts = $posts->filter(function($post)
{
if( !empty($province_id) && $province_id>0 )
{
return $post->where('province_id','=',$province_id);
}
})->values();
return $posts;
}
Any help appreciated.
First off, you should really do a validation for the id being larger than 0, if they were provided. You shouldn't be manually checking that out.
But anyhow, why are you using filter, when you can just directly use Eloquent (I omitted the check for id being bigger than 0):
$type_id = Input::get('type_id');
$country_id = Input::get('country_id');
$province_id = Input::get('province_id');
$query = Posting::query();
if ( ! empty($type_id)) $query->whereTypeId($type_id);
if ( ! empty($country_id)) $query->whereCountryId($country_id);
if ( ! empty($province_id)) $query->whereProvinceId($province_id);
return $query->get();
First off, you need to return something that makes sense from the closure in your filter:
$posts = $posts->filter(function($post)
{
if( !empty($type_id) && $type_id>0 )
{
return $post->where('type_id','=',$type_id);
}
})
Above returns Eloquent\Builder object, which is evaluated to true, so.. it really doesn't make sense.
This is what you need:
$posts = $posts->filter(function($post)
{
if( !empty($type_id) && $type_id>0 )
{
return $post->type_id == $type_id; // bool
}
})
With such code, you will filter the collection. $posts now will hold only those items, that match the statement in that closure.

CI pagination double query

I am working in CI Framework. For pagination i use two queries, one for required output using limit, and another to count total number of rows. Is there any other way like both can be done from single query?
My query is:
{
$searchtxt = $this->input->post('searchtxt');
$datefrom = $this->input->post('fromdate');
$todate = $this->input->post('todate');
$status= $this->input->post('order_status');
$sc_id = $this->input->post('sc_id');
if($sc_id){
$this->db->where('('.'o.requested_sc_id = '.$sc_id.' OR o.requesting_sc_id = '.$sc_id.')');
//$this->db->where('o.requesting_sc_id =',$sc_id);
}
if ($status){
$this->db->where('o.order_status =',$status);
}
if ($status != '' && $status == 0 ){
$this->db->where('o.order_status = 0');
}
if($searchtxt){
$this->db->like('o.order_number',$searchtxt);
}
if($datefrom)
{
$this->db->where('o.order_dt >=', date("Y-m-d",date_to_timestamp($datefrom)));
}
if($todate)
{
$this->db->where('o.order_dt <=', date("Y-m-d",date_to_timestamp($todate)));
}
if ($this->session->userdata('usergroup_id')!=1 && $this->session->userdata('usergroup_id')!= 2 && $this->session->userdata('usergroup_id')!=6 ){
$this->db->where('('.'o.requested_sc_id = '.$this->session->userdata('sc_id').' OR o.requesting_sc_id = '.$this->session->userdata('sc_id').')');
//$this->db->where('o.requesting_sc_id = '.$this->session->userdata('sc_id'));
}
$this->db->select('o.order_id,o.order_number,o.order_dt,o.call_id,c.call_uid,o.order_status,o.order_dt,sc.sc_name,e.engineer_name');
$this->db->from($this->table_name.' AS o');
$this->db->join($this->mdl_callcenter->table_name.' AS c','c.call_id=o.call_id','left');
$this->db->join($this->mdl_servicecenters->table_name.' AS sc' ,'sc.sc_id=o.requested_sc_id','left');
$this->db->join($this->mdl_engineers->table_name.' AS e', 'e.engineer_id = o.engineer_id','left');
$this->db->order_by('o.order_status ASC,o.order_dt DESC,o.order_created_ts DESC');
if(isset($page['limit'])){
$this->db->limit((int)$page['limit'],(int)$page['start']);
}
$result = $this->db->get();
//echo $this->db->last_query();
if ($status){
$this->db->where('o.order_status =',$status);
}
if ($status != '' && $status == 0 ){
$this->db->where('o.order_status = 0');
}
if($sc_id){
$this->db->where('o.requesting_sc_id =',$sc_id);
}
if($searchtxt){
$this->db->like('o.order_number',$searchtxt);
}
if($datefrom)
{
$this->db->where('o.order_dt >=', date("Y-m-d",date_to_timestamp($datefrom)));
}
if($todate)
{
$this->db->where('o.order_dt <=', date("Y-m-d",date_to_timestamp($todate)));
}
//if ($this->session->userdata('global_admin')!=1){
if ($this->session->userdata('usergroup_id')!=1 && $this->session->userdata('usergroup_id')!= 2 && $this->session->userdata('usergroup_id')!=6 ){
$this->db->where('o.requested_sc_id = '.$this->session->userdata('sc_id').' or o.requesting_sc_id = '.$this->session->userdata('sc_id'));
}
$this->db->select('o.order_id');
$this->db->from($this->table_name.' AS o');
$this->db->join($this->mdl_callcenter->table_name.' AS c','c.call_id=o.call_id','left');
$this->db->join($this->mdl_servicecenters->table_name.' AS sc' ,'sc.sc_id=o.requested_sc_id','left');
$this->db->join($this->mdl_engineers->table_name.' AS e', 'e.engineer_id = o.engineer_id','left');
$result_total = $this->db->get();
$orders['list'] = $result->result();
$orders['total'] = $result_total->num_rows();
return $orders;
}
Here is some explanation for this.
function($limit,$offset){
$this->db
->select("SQL_CALC_FOUND_ROWS emp", FALSE)
->select("*")
->from('tbl1')
->limit($limit, $offset);
$data["query_result"] = $this->db->get()->result_array();
$query = $this->db->query('SELECT FOUND_ROWS() AS `Count`');
$data["total_rows"] = $query->row()->Count;
return $data;
}
Here you see you are forced to get total count using another query.
Of course this is not what you want but it is impossible with single query using mysql.
But here is a php way.
function($limit,$offset){
$this->db
->select("*")
->from('tbl1');
$data["query_result"] = $this->db->get()->result_array();
$data["total_rows"] = array_slice($data["query_result"], $offset, $limit);
return $data;
}
This can be achieved with single query but involves php to get the desired result.

Resources