How to display last query in laravel 5? - laravel

I use :
DB::connection()->enableQueryLog();
var_dump(DB::getQueryLog());
But it's not working.
My service is like this :
public function dataCustomerList($param)
{
$status = $param['status_sort'];
$gender = $param['gender'];
$published = $param['published'];
if($published=='NO'){
$published_check = 'NO';
$published = 0;
}
else if($published=='YES'){
$published_check = 'YES';
$published = 1;
}
DB::connection()->enableQueryLog();
$customer = customer::paginate(10);
if(!empty($status)) {
// die($status);
$customer = customer::where('tb_customer.customer_status', '=', $status)->paginate(10);
}
if (!empty($gender)) {
$customer = customer::where('tb_customer.gender', '=', $gender)->paginate(10);
}
if (!empty($published_check)) {
$customer = customer::where('tb_customer.published', '=', $published)->paginate(10);
}
var_dump(DB::getQueryLog());
return $customer;
}
When I run it, query does not appear
The result is like this :
array(0) {
}
How to get the query executed in Laravel 5?
Thank you very much

You could listen to query events on DB:
DB::listen(function($query) {
var_dump($query->sql);
});

Related

How can I update a column value given a where clause in Laravel?

I've tried doing:
$uniquekey = '202208271120';
$results2 =DB::table('tests')
->where('usuario_id', $usuario)
->where('id_evento_test', '0')
->update([ 'id_evento_test'=> $uniquekey]);
return response()->json($results2, 201);
but when testing it in postman returned me 0.
enter image description here
Here's my code:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class ShowSummaryResultsController extends Controller
{
public function show(Request $request)
{
$usuario = $request->input('usuario');
$results = DB::table('tests')
->where('usuario_id', '=', $usuario)
->where('id_evento_test', '=', '0')
->get();
$resultsOkPROTANOPIA = 0;
$resultsNokPROTANOPIA = 0;
$resultsOkDEUTERANOPIA = 0;
$resultsNokDEUTERANOPIA = 0;
$resultsOkTRITANOPIA = 0;
$resultsNokTRITANOPIA = 0;
foreach ($results as $rows)
{
$image_id = $rows->image_id;
$resultado = $rows->resultado;
//$tipo = DB::table('images')
//->where('id', '=', $image_id)
//->get();
$image = 'App\Models\Image'::findOrFail($image_id);
$tipo_discromatopsia = $image->tipo_discromatopsia;
if ($tipo_discromatopsia == 'PROTANOPIA') {
if($resultado) {
$resultsOkPROTANOPIA +=1;
}else{
$resultsNokPROTANOPIA +=1;
}
}
elseif ($tipo_discromatopsia == 'DEUTERANOPIA') {
if($resultado) {
$resultsOkDEUTERANOPIA +=1;
}else{
$resultsNokDEUTERANOPIA +=1;
}
}
else {
if($resultado) {
$resultsOkTRITANOPIA +=1;
}else{
$resultsNokTRITANOPIA +=1;
}
}
//update event_id with a unique key
//$uniquekey = 202208271116;
//$results->id_evento_test = $uniquekey;
//$results->save();
}
$porc=0;
if (($resultsOkPROTANOPIA + $resultsNokPROTANOPIA) >0)
{ $porc=$resultsOkPROTANOPIA / ($resultsOkPROTANOPIA + $resultsNokPROTANOPIA ) * 100; }
$result[0] = array("tipo" =>'PROTANOPIA',"ResOK" =>$resultsOkPROTANOPIA,"ResNOK" =>$resultsNokPROTANOPIA,"Porc" =>$porc);
$porc=0;
if (($resultsOkDEUTERANOPIA + $resultsNokDEUTERANOPIA ) >0)
{$porc=$resultsOkDEUTERANOPIA / ($resultsOkDEUTERANOPIA + $resultsNokDEUTERANOPIA ) * 100;}
$result[1] = array("tipo" =>'DEUTERANOPIA',"ResOK" =>$resultsOkDEUTERANOPIA,"ResNOK" =>$resultsNokDEUTERANOPIA,"Porc" =>$porc);
$porc=0;
if (($resultsOkTRITANOPIA + $resultsNokTRITANOPIA )>0)
{$porc=$resultsOkTRITANOPIA/ ($resultsOkTRITANOPIA + $resultsNokTRITANOPIA )* 100;}
$result[2] = array("tipo" =>'TRITANOPIA',"ResOK" =>$resultsOkDEUTERANOPIA,"ResNOK" =>$resultsNokDEUTERANOPIA,"Porc" =>$porc);
$min = min($result[0]['Porc'],$result[1]['Porc'],$result[2]['Porc']);
$result[3] = array("tipo" =>'RESULTADOS',"index"=>$min,"Tipo"=>$result[$min]['tipo'], );
$uniquekey = '202208271120';
$results2 =DB::table('tests')
->where('usuario_id', $usuario)
->where('id_evento_test', '0')
->update([ 'id_evento_test'=> $uniquekey]);
return response()->json($results2, 201);
//return response()->json($result, 201);
}
}
If you need value of column after successful updating then read this example please:
$uniquekey = '202208271120';
try {
DB::table('tests')
->where('usuario_id', $usuario)
->where('id_evento_test', 0)
->update(['id_evento_test' => $uniquekey]);
$results2 = $uniquekey;
return response()->json($results2, 201);
} catch (\Illuminate\Database\QueryExeption $e) {
return response()->json(['error' => 'Unsuccessful Update']);
}
You can use first or get to retrieve all the data from table test or only column id_evento_test. So $results2 could have all data or only part of data as you need.
in this code $results2 =DB::table('tests') you are storing the result of the database query to $result2 which is 0 or 1 and 0 means that nothing was updated and 1 means that the update was done successfully.
if you want to return the $uniquekey then assign it to $result2:
$results2 = $uniquekey;
return response()->json($results2, 201);
or just return $uniquekey:
return response()->json($uniquekey, 201);

Best way convert json string to Laravel Query Builder?

i have a filter string, what do you think how can i convert laravel query builder? I used some ways but I wasn't sure.
filter: [["id","=",2],"or",["id","=",3],"and",["name","LIKE", "%John%"]]
Thank you.
if ($request->get('filter')) {
$filter = json_decode($request->get('filter'));
if (gettype($filter[0]) === 'string') {
list($field, $id) = $filter;
$query->where($field, $id);
} elseif (gettype($filter[0]) === 'array') {
foreach ($filter as $value) {
if (gettype($value) === 'string') {
switch ($value) {
case 'or':
//
break;
case 'and':
//
break;
}
} elseif (gettype($value) === 'array') {
list($field, $clause, $id) = $value;
}
}
}
}
Maybe something like this:
$arr = [["id","=",2],"or",["id","=",3],"and",["name","LIKE", "%John%"]];
$query = Model::query(); // build the empty query
if(size($arr) > 0){ // if there is at least 1 element
$query->where(...$arr[0]); // apply that element
for($i = 1; $i < size($arr); $i+=2){ // for every other entry, loop through them 2 by 2 and based of the current one, apply orWhere or where
if($arr[$i] === "or")
$query->orWhere(...$arr[$i+1]);
else
$query->where(...$arr[$i+1]);
}
}
$result = $query->get();

Codeigniter3.x calling multiple stored procedure cache

This is somewhat related to [CodeIgniter active records' problems calling multiple stored procedures
but I am not experiencing a blank page; instead when I am passing my data array to view it seems that the the preceding array also being drag to the view.
model
public function data1($student) {
$year = 1;
$sem = 1;
$course = $this->getStudentCourseByStudentId($student);
$sql = "CALL EVALUATION_BY_YEAR_SEM(?,?,?,?)";
$query = $this->db->query($sql, array($course, $student, $year, $sem));
if (!$query) {
return $this->db->error();
} else {
mysqli_next_result( $this->db->conn_id );
return $query->result();
}
}
public function data2($student) {
$year = 1;
$sem = 2;
$course = $this->getStudentCourseByStudentId($student);
$sql = "CALL EVALUATION_BY_YEAR_SEM(?,?,?,?)";
$query = $this->db->query($sql,array($course,$student,$year,$sem));
if (!$query) {
return $this->db->error();
} else {
mysqli_next_result( $this->db->conn_id );
return $query->result();
}
}
Controller:
$data['data1']=data1 from my model(SP);
$data['data2']=data2 from my model(SP);
View:
foreach($data2 as key => $value ) {
echo ....;
}
Here's the PROBLEM... in the view, I only wanted to output the $data2 but to my surprise $data1 is also being output.
Does anybody else have this issue?
I JUST SOLVE IT.
Model
public function data1($student){
**$this->db->initialize();**
$year = 1;$sem = 1;
$course = $this->getStudentCourseByStudentId($student);
$sql = "CALL EVALUATION_BY_YEAR_SEM(?,?,?,?)";
$query = $this->db->query($sql,array($course,$student,$year,$sem));
if (!$query) {
return $this->db->error();
}else {
mysqli_next_result( $this->db->conn_id );
return $query->result();**$this->db->close();**
}
}
public function data2($student){
**$this->db->initialize();**
$year = 1;$sem = 2;
$course = $this->getStudentCourseByStudentId($student);
$sql = "CALL EVALUATION_BY_YEAR_SEM(?,?,?,?)";
$query = $this->db->query($sql,array($course,$student,$year,$sem));
if (!$query) {
return $this->db->error();
}else {
mysqli_next_result( $this->db->conn_id );
return $query->result();**$this->db->close();**
}
}
controller
$data['data1']=data1 from my model(SP);
**$this->db->close();**
$data['data2']=data2 from my model(SP);

laravel advanced wheres not working

my function with advanced wheres is not giving any syntax error but its not even working. Its displaying. i have written this function following this example http://laravel.com/docs/queries#advanced-wheres
public function getData($wheres1 = array(),$wheres2 = array(),$wheres3 = array(),$wheres4 = array(),$wheres5 = array(),$wheres6 = array(),$wheres7 = array())
{
$query = Listing::query();
$result = array();
$query = $query->where(function($q){
if(!empty($wheres1)){
$count=0;
foreach($wheres1 as $where){
if($count==0)
{ $q = $q->where($where['field'], $where['operator'], $where['value']);
$count++;
}
else
$q = $q->orWhere($where['field'], $where['operator'], $where['value']);
}
}
})->where(function($q){
if(!empty($wheres2)){
$count=0;
foreach($wheres2 as $where){
if($count==0)
{ $q = $q->where($where['field'], $where['operator'], $where['value']);
$count++;
}
else
$q = $q->orWhere($where['field'], $where['operator'], $where['value']);
}
}
})->where(function($q){
if(!empty($wheres3)){
$count=0;
foreach($wheres3 as $where){
if($count==0)
{ $q = $q->where($where['field'], $where['operator'], $where['value']);
$count++;
}
else
$q = $q->orWhere($where['field'], $where['operator'], $where['value']);
}
}
});
$result = $query->orderBy('id', 'desc')->paginate(3);
return $result;
}
You need to add use for each where
$query = $query->where(function($q) use ($wheres1) {
....
}
You may try this approach:
$query = Listing::query();
if(is_array($wheres1) && count($wheres1)) {
$first = array_shift($wheres1);
$query->where($first['field'], $first['operator'], $first['value']);
if(count($wheres1)) {
foreach($wheres1 as $where) {
$query->orWhere($wheres['field'], $wheres['operator'], $wheres['value']);
}
}
}
Now repeat the same process for rest of the wheres, for example ($wheres2):
if(is_array($wheres2) && count($wheres2)) {
$first = array_shift($wheres2);
$query->where($first['field'], $first['operator'], $first['value']);
if(count($wheres2)) {
foreach($wheres2 as $where) {
$query->orWhere($wheres['field'], $wheres['operator'], $wheres['value']);
}
}
}
At last:
return $query->orderBy('id', 'desc')->paginate(3);

Best Practice: Models and Controllers

I would like to get your MVC experience on the following:
I have a table where I say which user_id is in which group_id and a second table where I say which user_id has which user_name.
Now I want a function to which I pass a group_id and it gives me all user_names in the group.
The question is, what does the Controller do and what the Model:
Controller calls a Model (get_user_ids_from_group) that returns the user ids and then the controler calls different model (get_user_name_by_id) to return the usernames.
A controller calls a Model (`get_user_names_from_group) and the model internally gets first the user ids and then the user names.
I understand that the first way is more MVC strict. But how strict would you be in a case like this? Right now I am always being very strict.
As a result my model functions have always just two lines (query and return) and my controller are bigger. So to make controller and model size more equal the second option would be possible.
Actually, it has nothing to do with MVC, as CodeIgniter doesn't implement MVC, but a sort of MVP.
However, if you're using RDBMS such as MySQL, you could JOIN these two table (within the Model) and fetch the result (within the Controller) as I suggested in a similar topic on SO.
application/models/user.php
class User extends CI_Model
{
public function get_users_by_group($group_id)
{
$this->db->select('*')->from('groups');
// While group_id and user_id have a N:1 relation
$this->db->where('group_id', $group_id);
$this->db->join('users', 'users.user_id = groups.user_id');
$query=$this->db->get();
return $query->result_array();
}
}
Then fetch and pass the result within the Controller:
application/controllers/users.php
class Users extends CI_Controller
{
public function view($group_id)
{
$this->load->model('user');
// Fetch the result from the database
$data['users'] = $this->user->get_users_by_group($group_id);
// Pass the result to the view
$this->load->view('users_view', $data);
}
}
In MVC model should not be only use for storing and getting the data but also it should contain the business logic.
Controller - Should take input communicate with model and view
Model - Should contain business logic and data store
View - Only for Output
So its like Input -> Process -> Output
Also its depend on you where to put what and you should have a balance code on controller and model, Not write everything in controller or in model
In you case I think you should uses get_user_names_from_group and just pass the group name and make a join query between two table. And when you define your function in the model its give you the option to reuse the function again in case you need same thing on next controller.
Common model example:
<?php
class Common_model extends CI_Model {
function get_entry_by_data($table_name, $single = false, $data = array(), $select = "", $order_by = '', $orderby_field = '', $limit = '', $offset = 0, $group_by = '') {
if (!empty($select)) {
$this->db->select($select);
}
if (empty($data)) {
$id = $this->input->post('id');
if (!$id)
return false;
$data = array('id' => $id);
}
if (!empty($group_by)) {
$this->db->group_by($group_by);
}
if (!empty($limit)) {
$this->db->limit($limit, $offset);
}
if (!empty($order_by) && !empty($orderby_field)) {
$this->db->order_by($orderby_field, $order_by);
}
$query = $this->db->get_where($table_name, $data);
$res = $query->result_array();
//echo $this->db->last_query();exit;
if (!empty($res)) {
if ($single)
return $res[0];
else
return $res;
} else
return false;
}
public function get_entry_by_data_in($table_name, $single = false, $data = array(), $select = "", $order_by = '', $orderby_field = '', $limit = '', $offset = 0, $group_by = '',$in_column='',$in_data=''){
if (!empty($select)) {
$this->db->select($select);
}
if (empty($data)) {
$id = $this->input->post('id');
if (!$id)
return false;
$data = array('id' => $id);
}
if (!empty($group_by)) {
$this->db->group_by($group_by);
}
if (!empty($limit)) {
$this->db->limit($limit, $offset);
}
if (!empty($order_by) && !empty($orderby_field)) {
$this->db->order_by($orderby_field, $order_by);
}
if (!empty($in_data) and !empty($in_column)) {
$this->db->where_in($in_column,$in_data);
}
$query = $this->db->get_where($table_name, $data);
$res = $query->result_array();
//echo $this->db->last_query();exit;
if (!empty($res)) {
if ($single)
return $res[0];
else
return $res;
} else
return false;
}
public function getAllRecords($table, $orderby_field = '', $orderby_val = '', $where_field = '', $where_val = '', $select = '', $limit = '', $limit_val = '') {
if (!empty($limit)) {
$offset = (empty($limit_val)) ? '0' : $limit_val;
$this->db->limit($limit, $offset);
}
if (!empty($select)) {
$this->db->select($select);
}
if ($orderby_field)
$this->db->order_by($orderby_field, $orderby_val);
if ($where_field)
$this->db->where($where_field, $where_val);
$query = $this->db->get($table);
//return $query->num_rows;
//echo $this->db->last_query();
if ($query->num_rows > 0) {
return $query->result_array();
}
}
function alldata($table) {
$query = $this->db->get($table);
return $query->result_array();
}
function alldata_count($table, $where) {
$query = $this->db->get_where($table, $where);
return $query->num_rows();
}
function insert_entry($table, $data) {
$this->db->insert($table, $data);
return $this->db->insert_id();
}
function update_entry($table_name, $data, $where) {
return $this->db->update($table_name, $data, $where);
}
public function get_data_by_join($table, $table2, $where, $table1_column, $table2_column, $limit = '', $order_column = '', $order_by = 'DESC', $select_columns = '', $is_single_record = false, $group_by = '', $join_by = '', $offset = '') {
if (!empty($select_columns)) {
$this->db->select($select_columns);
} else {
$this->db->select('*');
}
$this->db->from($table);
$this->db->join($table2, $table . '.' . $table1_column . '=' . $table2 . '.' . $table2_column, $join_by);
$this->db->where($where);
if (!empty($limit)) {
if (!empty($offset)) {
$this->db->limit($limit, $offset);
} else {
$this->db->limit($limit);
}
}
if (!empty($order_column)) {
$this->db->order_by($order_column, $order_by);
}
if (!empty($group_by)) {
$this->db->group_by($group_by);
}
$query = $this->db->get();
if ($query->num_rows() > 0) {
if ($is_single_record) {
$rs = $query->result_array();
return $rs[0];
} else {
return $query->result_array();
}
} else {
return false;
}
}
function DeleteRecord($table_name, $where) {
return $this->db->delete($table_name, $where);
}
function managerecord() {
$count = 1;
$where = array('channel_id' => 8,
'field_id_12 !=' => '');
$this->db->where($where);
$query = $this->db->get('channel_data');
$data = $query->result_array();
foreach ($data as $value) {
$id = $value['field_id_12'];
$update = array('telephone' => $value['field_id_53'],
'about' => $value['field_id_54'],
'license' => $value['field_id_18'],
'broker' => $value['field_id_19'],
'preferred' => 'yes');
$this->db->update('members', $update, array('member_id' => $id));
}
echo "done1";
}
public function get_content_landing_page($table = false, $field = false, $id = false, $id_name = false) {
$this->db->select($field);
$this->db->from($table);
$this->db->where($id_name, $id);
$query = $this->db->get();
return $query->result_array();
}
public function get_field_landing_page($id = false,$fields=false) {
$this->db->select($fields);
$this->db->from('terratino_form_fields_master');
$this->db->where('id', $id);
$query = $this->db->get();
return $query->result_array();
}
}
?>

Resources