laravel using whereBetween for count multiple table - laravel

function fetch_c(Request $request)
{
if($request->ajax())
{
if($request->from_date != '' && $request->to_date != '')
{
$data = DB::select("SELECT (SELECT COUNT(*) FROM pos) as a, (SELECT COUNT(*) FROM customers) as b, (SELECT COUNT(*) FROM
supplires) as c")
->whereBetween('created_at', array($request->from_date, $request->to_date));
}
else
{
$data = DB::select("SELECT (SELECT COUNT() FROM pos) as a, (SELECT COUNT() FROM customers) as b, (SELECT COUNT(*) FROM
supplires) as c");
}
echo json_encode($data);
}
}

function fetch_c(Request $request)
{
if($request->ajax())
{
if($request->from_date != '' && $request->to_date != '')
{
$data = DB::select("SELECT (SELECT COUNT(*) FROM pos) as a, (SELECT COUNT(*) FROM customers) as b, (SELECT COUNT(*) FROM supplires) as c")
->whereBetween('created_at', array($request->from_date, $request->to_date));
}
else
{
$data = DB::select("SELECT (SELECT COUNT(*) FROM pos) as a, (SELECT COUNT(*) FROM customers) as b, (SELECT COUNT(*) FROM supplires) as c");
}
echo json_encode($data);
}
}
ajax
<script>
$(document).ready(function(){
var date = new Date();
$('.input-daterange').datepicker({
todayBtn: 'linked',
format: 'yyyy-mm-dd',
autoclose: true
});
var _token = $('input[name="_token"]').val();
fetch_data();
function fetch_data(from_date = '', to_date = '')
{
$.ajax({
url:"{{ url('fetch_c') }}",
method:"get",
data:{from_date:from_date, to_date:to_date},
dataType:"json",
success:function(data)
{
console.log(data);
// $("#max_score").val(data);
}
})
$('#filter').click(function(){
var from_date = $('#from_date').val();
var to_date = $('#to_date').val();
if(from_date != '' && to_date != '')
{
fetch_data(from_date, to_date);
}
else
{
alert('Both Date is required');
}
});
});
</script>
Route
Route::get('/fetch_c', [App\Http\Controllers\HomeController::class, 'fetch_c']);
Error
GET http://localhost:8000/fetch_c?from_date=2022-03-01&to_date=2022-03-31 500 (Internal Server Error)

Related

Request input null in Laravel Controller

Hi I have a problem with getting the value of input using request in Controller, it's always return null. This is my code in jquery I am using Ajax to pass value to controller.
$('.generate').click(function(){
var dstart = $("#datepickerstart").val();
var dend = $("#datepickerend").val();
//var empid = $('#empid').val();
if($('#empid').val().length == 0)
{
empid = 0;
}
else{
empid = $('#empid').val();
}
var dStart = 0;
var dEnd = 0;
//alert(empid);
$.ajax({
type: "GET",
url: "{{route('manageattendance', '')}}"+"/"+empid,
data:$('#attendanceform').serialize(),
success: function(response)
{
console.log(response);
// alert("data caught");
$('.content').load('manageattendance/'+empid);
},
error: function(error)
{
console.log(error);
//alert("not caught ");
// alert($('#editForm').serialize());
}
});
//alert(dstart);
//alert(dend);
});
And this is my code in controller. I am trying to get the data using request but it returns null when I checked it. What would be the cause? Please help me. Thanks
public function index($id = 0,Request $request)
{
if($id == 0){
$current_date = date('Y-m-d');
$attendances = Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')-
>where('Date','=',$current_date)->get();
//$start = '2021-02-10';
//$end = '2021-02-11';
//$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->whereBetween('Date',
[$start,$end])->get();
return view('manage.index',compact('attendances'));
}
else
{
$start = $request->input('datepickerstart');
$end = $request->input('datepickerend');
$newS = date('Y-m-d', strtotime($start));
$newE = date('Y-m-d', strtotime($end));
$sUser = User::select('name')->where('id','=',$id)->get();
//$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->where('user_id','=',$id)-
>get();
$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->whereBetween('Date',
[$start,$end])->get();
return view('manage.index',compact('attendances','sUser'));
// dd($start);
}
// return view('manage.index');
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
}
don't forget {{csrf_field }} in form and put id in input name is id
$('.generate').click(function(){
var dstart = $("#datepickerstart").val();
var dend = $("#datepickerend").val();
//var empid = $('#empid').val();
if($('#empid').val().length == 0)
{
empid = 0;
}
else{
empid = $('#empid').val();
}
var dStart = 0;
var dEnd = 0;
//alert(empid);
$.ajax({
type: "GET",
url: "{{route('manageattendance.update')}}"+"/"+empid,
data:$('#attendanceform').serialize(),
success: function(response)
{
console.log(response);
// alert("data caught");
$('.content').load('manageattendance/'+empid);
},
error: function(error)
{
console.log(error);
//alert("not caught ");
// alert($('#editForm').serialize());
}
});
//alert(dstart);
//alert(dend);
});
public function index(Request $request)
{
if(request->id == 0){
$current_date = date('Y-m-d');
$attendances = Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')-
>where('Date','=',$current_date)->get();
//$start = '2021-02-10';
//$end = '2021-02-11';
//$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->whereBetween('Date',
[$start,$end])->get();
return view('manage.index',compact('attendances'));
}
else
{
$start = $request->input('datepickerstart');
$end = $request->input('datepickerend');
$newS = date('Y-m-d', strtotime($start));
$newE = date('Y-m-d', strtotime($end));
$sUser = User::select('name')->where('id','=',$request->id)->get();
$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->where('user_id','=',$request->id)->whereBetween('Date',
[$start,$end])-
>get();
return view('manage.index',compact(['attendances'=>$attendances,'sUser'=>$sUser]));
// dd($start);
}
}

Update Table without loops

There is a table foo and it has a column called fooPos. I ned to update the fooPos column with respect to id.
I have the following data
$id = [21,23,34,56,76];
$fooPos = [1,2,3,4,5];
How can I update this without using loops?
It's like 21(id) => 1(fooPos), 23 => 2, 34 =>3 etc.,
You have a solution with INSERT INTO ... ON DUPLICATE KEY UPDATE..., more details in here Multiple update
That solution can trigger an error if the ID doesn't exist and you have some other required fields. In that cas you ca use this solution:
$updateSets = [];
$ids = [21,23,34,56,76];
$fooPos = [1,2,3,4,5];
foreach ($ids as $key => $id) {
$updateSets[] = 'SELECT '.$id.' as set_id, '.$fooPos[$key].' as pos ';
}
$updateSetsString = implode(' UNION ALL ', $updateSets);
\DB::statement('UPDATE your_table JOIN ('.$updateSetsString.') up_set ON your_table.id = up_set.set_id SET your_table.pos = up_set.pos');
function updateTableWithoutQueryLoops()
{
try {
$id = collect([21,23,34,56,76]);
$fooPos = collect([1,2,3,4,5]);
// To check both parameters should have an equal number of elements.
if(count($id) == count($fooPos) ) {
$combinedValues = $id->combine($fooPos);
} else {
return 'Please check equal number of elements for give arrays.';
}
// Run foreach loop of Combined values
foreach ($combinedValues as $id => $fooPos) {
$id = (int) $id;
$cases[] = "WHEN {$id} then ?";
$params[] = $fooPos;
$ids[] = $id;
}
$ids = implode(',', $ids);
$cases = implode(' ', $cases);
$params[] = \Carbon\Carbon::now();
return \DB::update("UPDATE `foo` SET `fooPos` = CASE `id` {$cases} END, `updated_at` = ? WHERE `id` in ({$ids})", $params);
} catch (\Exception $e) {
return 'Exception message:' . $e->getMessage() . ' with code: ' . $e->getCode();
}
}
function updateTableWithoutQueryLoops()
{
try {
$id = collect([21,23,34,56,76]);
$fooPos = collect([1,2,3,4,5]);
// To check both parameters should have an equal number of elements.
if(count($id) == count($fooPos) ) {
$combinedValues = $id->combine($fooPos);
} else {
return 'Please check equal number of elements for give arrays.';
}
// Run foreach loop of Combined values
foreach ($combinedValues as $id => $fooPos) {
$id = (int) $id;
$cases[] = "WHEN {$id} then ?";
$params[] = $fooPos;
$ids[] = $id;
}
$ids = implode(',', $ids);
$cases = implode(' ', $cases);
$params[] = \Carbon\Carbon::now();
return \DB::update("UPDATE `foo` SET `fooPos` = CASE `id` {$cases} END, `updated_at` = ? WHERE `id` in ({$ids})", $params);
} catch (\Exception $e) {
return 'Exception message:' . $e->getMessage() . ' with code: ' . $e->getCode();
}
}

laravel ajax post doesn't return values

I am trying to perform ajax post in laravel. I have a controller "show_freeCars" awich gets some values from ajax post and performs the query to return the results. I have this:
public function show_freeCars() {
$starttime = Input::get('starttime');
$endtime = Input::get('endtime');
$enddate = Input::get('enddate');
$startdate = Input::get('startdate');
$classes = Input::get('classes');
$free_cars = DB::select('SELECT * FROM cars WHERE id NOT IN (select distinct c.id from cars as c '
. 'left join rentals as r on c.id = r.vehicle '
. 'where STARTTIME="' . $startdate . ' ' . $starttime . '" '
. 'AND ENDTIME="' . $enddate . ' ' . $endtime . '" '
. 'AND (r.status="REZERVATION" OR r.status="CHECK_OUT") '
. 'order by c.id) AND class= "' . $classes . '" ');
if (Request::ajax()) {
$response_values = array(
'success' => 1,
'values' => $free_cars,
);
return Response::json($response_values);
} else {
dd('error');
}
}
and javascript
jQuery('#form-reservation').submit(function()
{
var startdate = $('input[name$="startdate"]').val();
var starttime = $('input[name$="starttime"]').val();
var enddate = $('input[name$="enddate"]').val();
var endtime = $('input[name$="endtime"]').val();
var classes = $('input[name$="classes"]').val();
var url = $(this).attr("action");
jQuery.ajax({
url: url,
type: "post",
data: {
startdate: startdate,
starttime: starttime,
enddate: enddate,
endtime: endtime,
classes: classes
},
datatype: "json",
beforeSend: function()
{
jQuery('#ajax-loading').show();
}
})
.done(function(data)
{
$('#cars_table').empty()
if (data.success === 1)
{
var arr = data.values;
alert(arr);
}
else {
window.location = data.redirect_to;
}
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('Invalid Data');
});
return false;
});
It alerts an empty. But if i remove the lines $classes = Input::get('classes'); and AND class= "' . $classes . '" ' from controller it shows the results. The query is ok because I tested it with dd($free_cars) and it displays the list of cars. Just something is messed with ajax return values. Why it returns null?

Codeigniter logical operator

I ask the question before I was not getting anymore replies and I decide to re-post it if that will help. I hope i'm not doing anything wrong by re-posting?
$total_cost_for_A = $this->admin_model->total_cost_for_A($branch, $department, $date);
$total_cost_for_B = $this->admin_model->total_cost_for_B($branch, $department, $date);
The variables $total_cost_for_A and $total_cost_for_B hold the returned value from a mysql summation queries in the model. The queries return false if no record was found. Now, I'm trying to perform this operation.
if(($total_cost_for_A === FALSE) && ($total_cost_for_B === FALSE))
{
$data['no_record'] = 'No Record Found!';
$this->load->view('admin/bookings', $data);
}
else
{
$this->load->view('admin/summary', $data);
}
This test always fail and execute the else statement instead, which is not what. Any assistance will be appreciated. Thanks
Here are the functions
function total_cost_for_A($branch, $department, $date)
{
if($branch == 'Head Office' && $department == 'Summary')
{
$select_amount_paid = 'SELECT SUM(total_amount) total_amount FROM graphics_booking AS bk
WHERE bk.date = "'.$date.'"';
}
$result = $this->db->query($select_amount_paid);
if($result->num_rows() > 0)
{
return $result;
}
else
{
return FALSE;
}
}
function total_cost_for_B($branch, $department, $date)
{
if($branch == 'Head Office' && $department == 'Summary')
{
$total_LF_amount = 'SELECT SUM(total_amount) total_amount FROM large_format_print
WHERE date = "'.$date.'"';
}
$result = $this->db->query($total_LF_amount);
if($result->num_rows() > 0)
{
return $result;
}
else
{
return FALSE;
}
}
Try to change like this
$select_amount_paid = 'SELECT SUM(total_amount) total_amount FROM graphics_booking AS bk
WHERE date = '.$date;//i assume that date is an colum from graphics_booking
you are wrong with "bk.date" you can give directly if it is in your table with where condition and also try to avoid the same name for the function in the model and the varaible assigned.Try to change as different.otherwise your code looks good
No when u return u cannot return the entire , you need to return a row
so you need to do in your model as :
function total_cost_for_A($branch, $department, $date)
{
if($branch == 'Head Office' && $department == 'Summary')
{
$select_amount_paid = 'SELECT SUM(total_amount) total_amount FROM graphics_booking AS bk
WHERE bk.date = "'.$date.'"';
}
$result = $this->db->query($select_amount_paid);
if($result->num_rows() > 0)
{
return $result->row(); // you missed out here
}
else
{
return FALSE;
}
}
Same for the total_cost_for_B()

jqgrid php SELECT query problems

I am attempting to use a variable in my SELECT statement but I'm running into some very strange problems .code below.
do not work,none data!
Code:
$fid= $_GET['f'];
echo $fid;//prints 3
$SQL = "SELECT threadid, thumb, title, stage, status, startdate ,duedate, forumid FROM thread WHERE forumid = '$fid' ";
work fine!
**Code:**
$SQL = "SELECT threadid, thumb, title, stage, status, startdate ,duedate, forumid FROM thread WHERE forumid ='3' ";
thank you!
grid.php
<?php include ("add/add_config.php");?>
<?php include ("php/jqAutocomplete.php");?>
<?php include ("php/jqCalendar.php");?>
<?php include ("php/jqGrid.php");?>
<?php
ini_set("display_errors","1");
$fid= $_GET['f'];
include ("php/jqGridPdo.php");
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
$conn->query("SET NAMES utf8");
// Create the jqGrid instance
$grid = new jqGridRender($conn);
echo $fid;
$grid->SelectCommand ="SELECT threadid, thumb, title, stage, status, startdate ,duedate FROM thread WHERE forumid='3'";
//$g="SELECT threadid, thumb, title, stage, status, startdate ,duedate, forumid FROM thread WHERE forumid='$fid'";
//echo $g;
// set the ouput format to json
$grid->dataType = 'json';
$grid->table ="thread";
$grid->setPrimaryKeyId("threadid");
$grid->setUrl('grid.php');
$grid->cacheCount = true;
$grid->addCol(array(
"name"=>"actions",
"formatter"=>"actions",
"editable"=>false,
"sortable"=>false,
"resizable"=>false,
"fixed"=>true,
"width"=>60,
"formatoptions"=>array("keys"=>true)
), "first");
$grid->setGridOptions(array(
"caption"=>"cdbdev",
"rownumbers"=>true,
"toppager"=>true,
"rowNum"=>10,
"sortname"=>"threadid",
"hoverrows"=>true,
"rowList"=>array(10,20,50),
"postData"=>array("grid_recs"=>776),
"height"=>"auto",
"width"=>"auto"
));
$grid->addCol(array("name"=>"fileToUpload", "editable"=>true, "edittype"=>"file", "editrules"=>array("edithidden"=>true)));
$upload = <<<UPLOAD
function(formid) {
//These are needed for fileupload plugin
$(formid).attr("method","POST");
$(formid).attr("action","");
$(formid).attr("enctype","multipart/form-data");
$("<br/><button id='buttonUpload'>Upload</button>").insertAfter("#fileToUpload",formid);
// bind a event
$("#buttonUpload",formid).click(function(){
$.ajaxFileUpload({
url:'doajaxfileupload.php',
secureuri:false,
fileElementId:'fileToUpload',
dataType: 'json',
success: function (data, status) {
console.log(data);
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else{
$("#fileToUpload").val("");
alert(data.msg);
}
}
},
error: function (data, status, e)
{
alert(e);
}
});
return false;
});
}
UPLOAD;
$grid->setJSCode($upload);
$image = <<<CUSTOM
function formatImage(cellValue, options, rowObject) {
var imageHtml = "<img src='images/" + cellValue + "' originalValue='" + cellValue + "' />";
return imageHtml;
}
function unformatImage(cellValue, options, cellObject) {
return $(cellObject.html()).attr("originalValue");
}
function formatRating(cellValue, options, rowObject) {
var color = (parseInt(cellValue) > 0) ? "green" : "red";
var cellHtml = "<span style='color:" + color + "' originalValue='" +
cellValue + "'>" + cellValue + "</span>";
return cellHtml;
}
function unformatRating(cellValue, options, cellObject) {
return $(cellObject.html()).attr("originalValue");
}
CUSTOM;
$grid->setJSCode($image);
$grid->setSelect('stage', "SELECT id, name FROM selection where statid=1");
$grid->setSelect('status', "SELECT id,name FROM selection where statid=2 ");
$grid->setColProperty("threadid", array( "width"=>80 , "align"=>center));
$grid->setColProperty("stage", array( "width"=>120 , "align"=>center));
$grid->setColProperty("forumid", array( "width"=>0 ,));
$grid->setColProperty("status", array( "width"=>120 , "align"=>center ));
$grid->setColProperty("title", array( "width"=>280, "align"=>center ,"formatter"=>"showlink","formatoptions"=>array("baseLinkUrl"=>"showthread.php", "target"=>"_blank", "idName"=>"t")));
$grid->setColProperty("startdate", array("width"=>130,"align"=>center,
"formatter"=>"date",
"formatoptions"=>array("srcformat"=>"Y-m-d H:i:s","newformat"=>"m/d/Y")
)
);
$grid->setColProperty("duedate", array("width"=>130,"align"=>center,
"formatter"=>"date",
"formatoptions"=>array("srcformat"=>"Y-m-d H:i:s","newformat"=>"m/d/Y")
)
);
$grid->setColProperty("CustomerID", array("editrules"=>array("required"=>true)));
$grid->setAutocomplete("CustomerID",false,"SELECT CustomerID, CompanyName FROM customers WHERE CompanyName LIKE ? ORDER BY CompanyName",null,true,true);
$grid->setUserTime("m/d/Y");
$grid->setUserDate("m/d/Y");
$grid->setDatepicker("startdate",array("buttonOnly"=>false));
$grid->datearray = array('startdate');
$grid->setUserTime("m/d/Y");
$grid->setUserDate("m/d/Y");
$grid->setDatepicker("duedate",array("buttonOnly"=>false));
$grid->datearray = array('duedate');
$grid->navigator = true;
$grid->setNavOptions('navigator', array("cloneToTop"=>true,"excel"=>true,"add"=>false,"edit"=>false,"del"=>false,"view"=>false));
$grid->exportfile = 'Report.xls';
$grid->setNavOptions('navigator', array("cloneToTop"=>true,"pdf"=>true,"add"=>false,"edit"=>false,"del"=>false,"view"=>false));
$grid->inlineNav = true;
$grid->setNavEvent('edit', 'onInitializeForm', $upload);
$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>
What SQL engine are you using? If it's MySQL you can use:
echo mysql_error();
after running the select to see what error you're having
also try echoing the SELECT statement after generating it to make sure no additional whitespace etc is added to $fid

Resources