Refactor Laravel Eloquent Query - laravel

I want to filter data given from eloquent laravel. I have 4 date picker in my view, and I want when each of one has filled and has date the query change.
This is my code in controller
if ($start_publish && $end_publish && $start_close && $end_close) {
$data = Tender::where('published_at','>=',$start_publish)->where('published_at','<=',$end_publish)->where('closed_at','>=',$start_close)->where('closed_at','<=',$end_close);
}elseif (!$start_publish && $end_publish && $start_close && $end_close) {
$data = Tender::where('published_at','<=',$end_publish)->where('closed_at','>=',$start_close)->where('closed_at','<=',$end_close);
} elseif ($start_publish && !$end_publish && $start_close && $end_close) {
$data = Tender::where('published_at','>=',$start_publish)->where('closed_at','>=',$start_close)->where('closed_at','<=',$end_close);
} elseif (!$start_publish && !$end_publish && $start_close && $end_close) {
$data = Tender::where('closed_at','>=',$start_close)->where('closed_at','<=',$end_close);
} elseif ($start_publish && $end_publish && !$start_close && $end_close) {
$data = Tender::where('published_at','>=',$start_publish)->where('published_at','<=',$end_publish)->where('closed_at','<=',$end_close);
}
elseif ($start_publish && $end_publish && $start_close && !$end_close) {
...
...
...
} else {
$data = Tender::get();
}
Because I have 4 input, the number of states for the condition is equal to 16 and the code is messy.
Does anyone have an idea to refactor the code?

The idea: if your variable is set, you check it. Otherwise not
You could try with this ( this is an idea, not the actual code )
$builder = Tender::query();
if($start_publish) $builder->where('published_at','>=',$start_publish);
if($start_close) $builder->where('closed_at','>=',$start_close);
...
return $builder->get()
.... and so on

Related

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) .

I want to add Arabic characters using preg_match() function

function validate_name($name, $name_limit, $name_system){
if(preg_match("/^[a-zA-Z0-9]{1,}[_-]?[a-zA-Z0-9]{1,}[_-]?[a-zA-Z0-9]{1,}$/", $name) && strlen($name) <= $name_limit && !ctype_digit($name) && $name !== $name_system && strlen($name) >= 4){
$valid_name = 1;
}
else {
$valid_name = 0;
}
return $valid_name;
}

Call to undefined function mcrypt_decrypt() - CometChat Laravel

Hi I've already installed the CometChat, but I'm facing the following error:
Call to undefined function mcrypt_decrypt() in /home/vagrant/changeglobe/public/cometchat/integration.php on line 89
I'm using Homestead with Nginx for Laravel. I have read at many places that I need to enable mycrypt, but did not found any correct. Please let me know about this issue if you know. Thank you.
Try replacing the getUserID() function in /cometchat/integration.php file with the code below:
function getUserID() {
$userid = 0;
if (!empty($_SESSION['basedata']) && $_SESSION['basedata'] != 'null') {
$_REQUEST['basedata'] = $_SESSION['basedata'];
}
if (!empty($_REQUEST['basedata'])) {
if (function_exists('mcrypt_encrypt') && defined('ENCRYPT_USERID') && ENCRYPT_USERID == '1') {
$key = "";
if( defined('KEY_A') && defined('KEY_B') && defined('KEY_C') ){
$key = KEY_A.KEY_B.KEY_C;
}
$uid = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode(rawurldecode($_REQUEST['basedata'])), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
if (intval($uid) > 0) {
$userid = $uid;
}
} else {
$userid = $_REQUEST['basedata'];
}
}
if (!empty($_COOKIE['laravel_session'])) {
$session= cookie_decrypt($_COOKIE['laravel_session']);
$data = file_get_contents(dirname(dirname(dirname(__FILE__))).'/storage/framework/sessions/'.$session);
if (!empty($data)) {
$k = explode(';i:',$data);
$m = explode(';s:',$k[1]);
$userid = $m[0];
}
}
$userid = intval($userid);
return $userid;
}
If you are still facing issues please create a support ticket https://my.cometchat.com/tickets and our team will assist you.

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.

Pagination codeigniter with query search

i want to create codeigniter pagination in my search form, when i clicked submit,it successfully shows the query search but when i clicked the number page link or next page, it shows message "undefined variable rec" and "Fatal error: Call to a member function num_rows() on a non-object" ,i'm sure the query has been passed to variable $rec.
And i see the problem here when i change the page,the variable return to null, so variable $rec didn't get the value from 'post'.
my question: how do i keep the value from 'post' so the query will get the variable value when i change the page?
here is my controller:
public function search(){
$kat=$this->input->post('kategori');
$prov=$this->input->post('prov');
$kot=$this->input->post('kota');
if($kat=='' && $prov!='' && $kot!=''){
$rec=$this->db->query("select * from showall where id_prov='$prov' and id_kota='$kot' ");
}
else if($kot=='' && $kat!='' && $prov!=''){
$rec=$this->db->query("select * from showall where id_kat='$kat' and id_prov='$prov' ");
}
else if($kat=='' && $kot=='' && $prov!=''){
$rec=$this->db->query("select * from showall where id_prov='$prov' ");
}
else if($kat!='' && $prov=='' && $kot==''){
$rec=$this->db->query("select * from showall where id_kat='$kat' ");
}
else if($kat!='' && $prov!='' && $kot!=''){
$rec=$this->db->query("select * from showall where id_kat='$kat' and id_prov='$prov' and id_kota='$kot' ");
}
$dat=$rec;
$data['count']=$dat->num_rows();
if($data['count'] >0){
$data['db']=$rec;
$config['total_rows'] = $data['db']->num_rows();
$config['base_url'] = base_url().'index.php/lowongan/cari';
$config['per_page'] = 1;
$config['uri_segment'] = 3;
$this->pagination->initialize($config);
$data['paging'] = $this->pagination->create_links();
if($kat=='' && $prov!='' && $kot!=''){
$d = $this->db->get_where('showall',array('id_prov'=>$prov,'id_kota'=>$kot) ,$config['per_page'], $this->uri->segment(3));
}
else if($kot=='' && $kat!='' && $prov!=''){
$d= $this->db->get_where('showall',array('id_kat'=>$kat,'id_prov'=>$prov) ,$config['per_page'], $this->uri->segment(3));
}
else if($kat=='' && $kot=='' && $prov!=''){
$d = $this->db->get_where('showall',array('id_prov'=>$prov) ,$config['per_page'], $this->uri->segment(3));
}
if($kat!='' && $prov=='' && $kot==''){
$d = $this->db->get_where('showall',array('id_kat'=>$kat) ,$config['per_page'], $this->uri->segment(3));
}
else if($kat!='' && $prov!='' && $kot!=''){
$d = $this->db->get_where('showall',array('id_kat'=>$kat,'id_prov'=>$prov,'id_kota'=>$kot) ,$config['per_page'], $this->uri->segment(3));
}
$data['record']=$d;
$data1['kat']=$this->query->kategoriAll();
$data1['prov']=$this->query->showProv();
$data['q1']=$this->query->lokasi();
$data['q2']=$this->query->perusahaan();
$data['q3']=$this->query->kategori();
$this->load->view("user/head");
$this->load->view("user/bar",$data1);
$this->load->view( 'user/hal_cari',$data);
$this->load->view("user/footer");
}
else{
$data1['kat']=$this->query->kategoriAll();
$data1['prov']=$this->query->showProv();
$data['q1']=$this->query->lokasi();
$data['q2']=$this->query->perusahaan();
$data['q3']=$this->query->kategori();
$this->load->view("user/head");
$this->load->view("user/bar",$data1);
$this->load->view( 'user/kosong',$data);
$this->load->view("user/footer");
}
}
You need to keep the condition array in the URL using assoc_to_uri(). I am doing like below.
$this->load->model('classified_model','classified');
$ClassifiedList = $this->classified->searchPage($condition,'classified_view',$perPage,$page*$perPage);
$uriString = $this->uri->assoc_to_uri($condition);
$config['uri_segment'] = count($condition) * 2 + 4;
$base_url = site_url('classified/search/' . $uriString . '/page/');
$base_url = preg_replace("/\.[a-z]*$/","", $base_url);
$config['base_url'] = $base_url;
$config['per_page'] = 1;
To get the $condition from uri again use
$condition = $this->uri->uri_to_assoc();

Resources