In SQL query i want to add if statement. if latitude and longitude null in database then query will run and fill the value in database
$users = DB::table('users',IF ($user->lat && $user->lng == Null))->get();
foreach ($users as $user)
{
$response = Geocode::make()->address($user->zipcode);
if ($response) {
$lat = $response->latitude();
$lng = $response->longitude();
$city = $response->formattedAddress();
echo $response->locationType();
DB::table('users')
->where('id', $user->id)
->update(['lat' => $lat,'lng' => $lng,'city' => $city]);
}
}
$users = User::whereNull('lat')->whereNull('lng')->get();
foreach ($users as $user) {
$response = Geocode::make()->address($user->zipcode);
if ($response) {
$lat = $response->latitude();
$lng = $response->longitude();
$city = $response->formattedAddress();
echo $response->locationType();
$user->update(['lat' => $lat,'lng' => $lng,'city' => $city]);
}
}
More specific details:
$city = $response->raw()->address_components[1]['long_name'];
$state = $response->raw()->address_components[2]['long_name'];
$country = $response->raw()->address_components[3]['long_name'];
DB::table('users')->where([
['users.lat', '=', NULL],
['users.lng', '=', NULL])->get();
Related
enter image description here
I have several inputs in order to filter products in the online shop. My question is, how can I filter products if some inputs are left without being filled/chosen. How should I query?
public function find()
{
$categories = Category::all();
if (isset($_GET['submit'])) {
if (!empty($_GET['brand'])) {
$selectedBrand = $_GET['brand'];
echo 'You have chosen: ' . $selectedBrand;
} else {
echo 'Please select the value.';
}
$date = Request::get('date');
$name = Request::get('name');
$selected = $_GET['type'];
$data = DB::table('product')->where('product.type', $_GET['type'])
->where('product.name', $name)
->join('shop', 'product.id', '=', 'shop.product_id')
->where('shop.releasedate', $date)
->get();
return view('pages/catalog')->with(['product' => $data, 'categories' => $categories]);
}
}
You can first check if your fields are filled and continue to query your model with when method
Logic
$date = null;
if($request->filled('date)){
$date = $request->date;
}
// your other values can go here like above
$data = DB::table('product')->where('product.type', $_GET['type'])
->where('product.name', $name)
->join('shop', 'product.id', '=', 'shop.product_id')
->when($date, function ($query, $transmission) {
// this query runs only if $date is `true` (has a value and not empty)
return return $query->where('shop.releasedate','=', $date);
->orderBy('shop.created_at','desc);
}, function ($query) {
// something you want to return if the $date is `false` (empty)
})
->get();
I'm using Laravel 5.5.
I have Table centrals with Model Centrals
and table like this
my Controller
$from = $request->year_from;
$to = $request->year_to;
$month_from = $request->month_from;
$month_to = $request->month_to;
$param = $request->get('parameters_id', []);
$search = Centrals::whereIn('parameters_id', $param)
->where('type', 'Monthly')
->where('year', $from)
->whereBetween('months_id', [$month_from, $month_to])
->orderBy('year')
->get();
now how i get data
example request:
$request->year_from = 2016;
$request->month_from = 1; /* 1 =Jan*/
$request->year_from = 2018;
$request->month_from = 3; /* 3 =Mar*/
The following should do the trick:
$search = Centrals::whereIn('parameters_id', $param)
->where('type', 'Monthly')
->where(function($q) use ($yearFrom, $monthFrom) {
$q->where('year', '>', $yearFrom);
$q->orWhere(function($q2) use ($yearFrom, $monthFrom) {
$q2->where('year', $yearFrom);
$q2->where('month', '>=', $monthFrom);
});
})
->where(function($q) use ($yearTo, $monthTo) {
$q->where('year', '<', $yearTo);
$q->orWhere(function($q2) use ($yearTo, $monthTo) {
$q2->where('year', $yearTo);
$q2->where('month', '<=', $monthTo);
});
})->get();
I have a query in PHP(MySQL). I am fetching records from a table and returning them to a datatable.
The problem is it always returns 1 when I use count() with the query.
However, if I count the elements of the array, then the result is as expected. It returns all 8 records.
Following is my code:
public function job_order_detail_del($arr=array()) {
$count = 0;
$start = isset($arr['start'])?$arr['start']:0;
$length = isset($arr['length'])?$arr['length']:0;
$search = isset($arr['search'])?$arr['search']:'';
$orderBy = isset($arr['orderBy'])?$arr['orderBy']:'';
$orderDir = isset($arr['orderDir'])?$arr['orderDir']:'';
$aufnr = isset($arr['aufnr'])?$arr['aufnr']:0;
$aufpl = isset($arr['aufpl'])?$arr['aufpl']:0;
$type = isset($arr['type'])?$arr['type']:'';
$whr = array('h.stats' => '', 'h.bukrs' => Session::get('company'), 'h.delstats' => '');
if ($aufnr > 0)
$whr['a.aufnr'] = $aufnr;
if ($aufpl > 0)
$whr['a.aufpl'] = $aufpl;
$a = DB::table('zpp_afpo_h as h')
->leftjoin('zpp_afpo as a ', function($join) {
$join->on('a.aufnr', '=', 'h.aufnr')
->where('a.bukrs', '=', Session::get('company'))
->where('a.stats', '=', '');
})
->leftjoin('zpp_afvc as b ', function($join) {
$join->on('a.aufnr', '=', 'b.aufnr')
->on('a.aufpl', '=', 'b.aufpl')
->where('b.bukrs', '=', Session::get('company'))
->where('b.stats', '=', '');
})
->leftjoin('zpp_afru as c ', function($join) use($type) {
$join->on('c.aufnr', '=', 'b.aufnr')
->on('c.rueck', '=', 'b.rueck');
})
->where('c.type', '=', $type)
->where('c.bukrs', '=', Session::get('company'))
->where('c.stats', '=', '')
->where('c.delstats', '=', '')
->select('h.idat2', 'a.matnr', 'b.arbpl', 'a.gamng as total', 'b.rueck', 'h.priority', 'b.vornr', 'b.prev_startper', 'b.scrap', 'h.dispatch_date', 'h.order_start_dt', 'h.requirement_dt', 'h.ktxt', 'c.rmzhl', 'c.budat', 'c.aufnr', 'c.rework_lmnga', DB::raw('sum(c.lmnga) as sum_cnfrm'));
if ($aufnr == '') {
$a->where('h.idat2', '=', '0000:00:00');
}
$a->where($whr)
->groupby('b.rueck')
->groupby('c.rmzhl')
->groupby('c.counter');
if($orderBy!=''){
$a->orderBy($orderBy,$orderDir);
}
if($search!=''){
$dt_srch = implode('-',array_reverse(explode('-',$search)));
$a->where(function($query) use ($search,$dt_srch){
$query->where('c.aufnr','LIKE','%'.$search.'%')
->orWhere('a.matnr','LIKE','%'.$search.'%')
->orWhere('c.budat','LIKE','%'.$dt_srch.'%')
->orWhere('b.arbpl','LIKE','%'.$search.'%')
->orWhere('a.gamng','LIKE','%'.$search.'%');
});
}
if($length>0){
$get_rec = $a->skip($start)->take($length)->get();
}else{
$get_rec = $a->get();
$count = count($get_rec);
// $count = $a->count(); //Problem is here
return $count;
}
$arr = array();
foreach($get_rec as $l){
if($length>0 || Input::get('open') == 1 || Input::get('open') == 2){
$arr = DB::table('maras')
->where('matnr','=',$l->matnr)
->where('bukrs','=',Session::get('company'))
->where('stats','=','')
->where('delstats','=','')
->select(DB::raw('GROUP_CONCAT(distinct(matnr)) as mat'),DB::raw('GROUP_CONCAT(distinct(mdesc)) as mat_desc'))
->groupby('matnr')
->first();
$l->matnr = $arr->mat;
$l->mat_desc = $arr->mat_desc;
}
}
return $get_rec;
}
Please let me know the problem. Thanks in advance.
You are using count on groupBy element and count is returning only the grouped count. That's why it is returning only single row or 1. You could count the returned collections in this case like-
$count = $get_rec->count();
I want to calculate hargaLama and hargaBaru, then insert it into database. To do so, I retrieve hargaLama from a view in mysql to my controller while hargaBaru is a user input. Even though I'm using foreach I got Undefined variable hargaLama and I also got error
Unknown column 'kodeProduksi' in 'field list'.
Here's my controller:
public function proses_tambahBarang(){
$kode = $_POST['kode'];
$kodeProduksi = $_POST['kodeProduksi'];
$nama = $_POST['nama'];
$tipe = $_POST['tipe'];
$ukuran = $_POST['ukuran'];
$merk = $_POST['merk'];
$satuan = $_POST['satuan'];
$jumlah = $_POST['jumlah'];
$harga = $_POST['hargaSatuan'];
// echo "proses_tambahBarang";
$data_insert = array(
'kodeBarang' => $kode,
'kodeProduksi' => $kodeProduksi,
'namaBarang' => $nama,
'tipeBarang' => $tipe,
'ukuran' => $ukuran,
'merk' => $merk,
'satuan' => $satuan,
'jumlah' => $jumlah,
'hargaSatuan' => $harga,
'keterangan' => 'n/a',
'idUser' => $this->session->userdata('username'),
'waktuMasuk' => 'n/a',
'waktuEdit' => 'n/a'
);
//$cek = $this->mhome->Barang("where kodeBarang = $data_insert[kodeBarang]");
// if($cek >= 1)
// {
$cek = $this->mhome->BarangHistory("where kodeProduksi = '$data_insert[kodeProduksi]'");
// $cek = $this->db->get_where('baranghistory',array('kodeProduksi' =>$data_insert['kodeProduksi']));
if($cek >= 1);
{
$query = $this->mhome->TableSelect('listBarang',"where kodeProduksi = '$data_insert[kodeProduksi]'");
foreach ($query as $row) {
$hargaLama = $row[0]['hargaSatuan'];
$jumlahLama = $row[0]['jumlah'];
}
$hargaBaru = $data_insert['hargaSatuan'];
$jumlahBaru = $data_insert['jumlah'];
$jumlahBaru = $jumlahBaru + $jumlahLama;
$data_insert['jumlah'] = $jumlahBaru;
$data_insert['waktuEdit'] = date("Y-m-d h:i:sa");
$data_insert['keterangan'] = "Updated";
$this->mhome->UpdateData('baranghistory',$data_insert,array("kodeProduksi" => $data_insert['kodeProduksi']));
$this->mhome->UpdateData('barang',$data_insert,array("kodeBarang" => $data_insert['kodeBarang']));
}
// $this->mhome->hitungHargaSatuan("where kodeBarang = '$data_insert[kodeBarang]'");
$hitung = $this->mhome->hitungHargaSatuan($data_insert['kodeBarang']);
if($hitung){
$this->session->set_flashdata('pesan','Tambah Barang Sukses');
redirect('userhome/index');
}
if($cek == 0) {
$data_insert['waktuMasuk'] = date("Y-m-d h:i:sa");
$data_insert['keterangan'] = "Baru";
$res = $this->mhome->InsertData('barang',$data_insert);
$res2 = $this->mhome->InsertData('baranghistory',$data_insert);
}
if($res >= 1 && $res2 >=1)
{
$this->session->set_flashdata('pesan','Tambah Barang Sukses');
redirect('userhome/index');
}
else {
echo "Tambah barang gagal";
}
}
And here's my model:
public function TableSelect($table,$where="")
{
$stmt = $this->db->query('select * from '.$table.' '.$where);
return $stmt->result_array();
}
I am sure you need not to put 0 here
foreach ($query as $row) {
$hargaLama = $row['hargaSatuan'];//remove [0] from here
$jumlahLama = $row['jumlah'];//remove [0] from here
}
like this.you need to use count on codition because this is returned array.and use result_array() for getting result in array format.
$cek = $this->mhome->BarangHistory("where kodeProduksi = $data_insert['kodeProduksi']")->result_array();
// $cek = $this->db->get_where('baranghistory',array('kodeProduksi' =>$data_insert['kodeProduksi']))->result_array();
if(count($cek) >= 1);
{
$query = $this->mhome->TableSelect('listBarang',"where kodeProduksi = $data_insert['kodeProduksi']");
foreach ($query as $row) {
$hargaLama = $row['hargaSatuan'];
$jumlahLama = $row['jumlah'];
}
I'm having a problem while running this code:
//DashboardController
public function getStream()
{
$user = Sentry::getUser();
$userid = $user->id;
$convs = TBMsg::getUserConversations($userid);
$getNumOfParticipants = $convs->getNumOfParticipants();
$participants = $convs->getAllParticipants();
$lastMessage = $convs->getLastMessage();
$senderId = $lastMessage->getSender();
$content = $lastMessage->getContent();
$status = $lastMessage->getStatus();
$posts = Post::whereIn('user_id', function($query) {
$query->select('follow_id')
->from('user_follows')
->where('user_id', '1');
})->orWhere('user_id', '1')->get();
return View::make('stream', array('getNumOfParticipants' => $getNumOfParticipants,
'participants' => $participants,
'lastMessage' => $lastMessage,
'senderId' => $senderId,
'content' => $content,
'status' => $status
))->with('posts', $posts)->with('convs', $convs);
}
}
I got this error: Call to undefined method Illuminate\Support\Collection::getNumOfParticipants()
http://i.stack.imgur.com/9N3xU.png
Replace ->get() with ->first() as right now you're basically returning an collection of arrays but you need that.
$query->select('follow_id')
->from('user_follows')
->where('user_id', '1');
})->orWhere('user_id', '1') // ->get() is removed
->first();
$convs is a collection so you can't call a method on it that only exists on a single model. Like the tutorial of the package suggests you have to iterate over the collection to use that function.
From the how to:
foreach ( $convs as $conv ) {
$getNumOfParticipants = $conv->getNumOfParticipants();
$participants = $conv->getAllParticipants();
/* $lastMessage Tzookb\TBMsg\Entities\Message */
$lastMessage = $conv->getLastMessage();
$senderId = $lastMessage->getSender();
$content = $lastMessage->getContent();
$status = $lastMessage->getStatus();
}