In my Laravel project, I have a BusController.php file where I need to run a for() loop. However, the loop is not working. I also tried a blade for looping but have the same problem.
BusController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Bus;
use App\Bus_type;
use App\Company;
use App\Http\Requests;
class BusController extends Controller
{
public function index()
{
$buses = Bus::all();
$bus_types = Bus_type::all();
$companies = Company::all();
return view('admin.adding_bus', compact('buses', 'bus_types', 'companies'));
}
public function store(Request $request)
{
$bus = new Bus;
$bus->company_name = $request->company_name;
$bus->bus_type = $request->bus_type;
$bus->bus_number = $request->bus_number;
$bus->no_of_rows = $request->no_of_rows;
$bus->no_of_columns = $request->no_of_columns;
$seats = "";
for ($i = 1; $i <= ($request->no_of_rows * $request->no_of_columns); $i++) {
$seats = $seats . "b";
}
$bus->seats = $seats;
$bus->save();
$buses = Bus::all();
$bus_types = Bus_type::all();
$companies = Company::all();
return view('admin.adding_bus', compact('buses', 'bus_types', 'companies'));
}
}
Make sure you have validated the data you received from the Request. Because if you don't the loop will be fail since the loop condition will always be false.
And to test it, here's what I do:
$seats = "";
$num_cols = 2;
$num_rows = ''; // assume you don't validate the request, so this can receive empty string too
// $num_rows = 0; // will output the same as above
for($i = 1;$i<=($num_cols * $num_rows);$i++)
{
$seats = $seats."b";
}
var_dump($seats);
Output:
string(0) ""
And here it is working one:
$seats = "";
$num_cols = 2;
$num_rows = 20; // correctly validated as integer and must be more than 0 because you're doing multiplication here in the following loop
for($i = 1;$i<=($num_cols * $num_rows);$i++)
{
$seats = $seats."b";
}
var_dump($seats);
Output:
string(40) "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
Related
i have bill and product_bill tables.
i need to use bill_id in product_bill table and i should create bill first ,
so id did this
public function store(Request $request)
{
if( Bill::first() == null )
{
$bill_id = 1;
}
else {
$bill_id = Bill::orderBy('id','desc')->first()->id +1 ;
}
// dd($bill_id);
$brand_id = auth('brand')->id();
$bill = new Bill();
$bill->brand_id = $brand_id;
$bill->date = Carbon::today();
$data = $request->all();
$products = [];
$total = 0;
for($i = 0 ; $i<count($data['id']) ; $i++)
{
$prod = new ProductsBill();
$prod->product_id = $data['id'][$i] ;
$prod->quantity = $data['quantity'][$i];
$prod->bill_id = $bill_id;
$products[] = $prod->attributesToArray();
$price = Product::find($prod->product_id)->price;
$total += $price * $prod->quantity;
}
$bill->total = $total;
$bill->save();
ProductsBill::insert($products);
return redirect()->back();
}
when i delete any bill the new bill_id in product_bill table get the next number for last one,
i need to know the id will be create next
thanks.
If you use save() function on your $bill variable, you will get the id by accessing $bill->id. If you want to ensure that you transaction is completed, you could use DB transactions.
use DB;
class ... {
...
public function store(Request $request)
{
$brand_id = auth('brand')->id();
$bill = new Bill();
$bill->brand_id = $brand_id;
$bill->date = Carbon::today();
DB::beginTransaction();
try{
$bill->save();
$data = $request->all();
$products = [];
$total = 0;
for($i = 0 ; $i<count($data['id']) ; $i++)
{
$prod = new ProductsBill();
$prod->product_id = $data['id'][$i] ;
$prod->quantity = $data['quantity'][$i];
$prod->bill_id = $bill->id;
$products[] = $prod->attributesToArray();
$price = Product::find($prod->product_id)->price;
$total += $price * $prod->quantity;
}
$bill->total = $total;
$bill->save();
ProductsBill::insert($products);
DB::commit();
return redirect()->back();
} catch(\Illuminate\Database\QueryException $ex){
DB::rollBack();
// Exception redirect here
}
}
...
}
If I understand your issue correctly, you could probably use the mysql functions to get the last inserted ID and add one to that.
https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_last-insert-id
I'm new in Laravel and PHPUnit. I'm trying to test controller, which read .json file, execute some calculation and returning result like this [3,3,2,0.5].
How can i send .json file or some value to controller and check feedback results?
Thank you in advance
controller:
namespace App\Http\Controllers;
class payController extends Controller
{
public function index()
{
$ratio = [];
$ratio1= [];
$string = file_get_contents("input.json");
if(!isset($string)){
echo 'File is empty.';
} else {
$json_a = json_decode($string, true);
$required_income = $json_a['required_income'];
foreach ($json_a['sms_list'] as $json) {
$ratio_value = $json['income'] * 100 / $json['price'];
array_push($ratio, [$ratio_value, $json['price'], $json['income']]);
}
foreach ($json_a['sms_list'] as $json) {
array_push($ratio1, [$json['price'], $json['income']]);
}
$count = count($ratio);
rsort($ratio, 0);
$smsPrice = [];
for ($i = 0; $i < $count; $i++) {
$price = $ratio[$i][1];
$income = $ratio[$i][2];
$divisionRequiredIncome = floor($required_income / $price);
if ($divisionRequiredIncome > 0) {
for ($j = 0; $j < $divisionRequiredIncome; $j++) {
array_push($smsPrice, $price);
}
$required_income -= ($income * $divisionRequiredIncome);
}
}
sort($ratio1, 1);
for ($i = 0; $i < $count; $i++) {
if ($required_income - $ratio1[$i][1] <= 0) {
array_push($smsPrice, $ratio1[$i][0]);
break;
}
}
}
echo '<pre>';
var_dump($smsPrice);
}
}
payControllerTest:
namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Http\Controllers\payController;
class payControllerTest extends TestCase
{
/**
* A basic unit test example.
*
* #return void
*/
public function test_first()
{
$res = payController::index();
}
}
input.json file:
{
"sms_list": [
{"price": 0.5, "income": 0.41},
{"price": 1, "income": 0.96},
{"price": 2, "income": 1.91},
{"price": 3, "income": 2.9}
],
"required_income": 8
}
I've got a web service which takes around 15 secs to return JSON response to front-end.My code looks like this:
Controller code:
public function getDetailReport($data){
$user_id = $data->user_id;
$test_id = $data->test_id;
$result_obj = new TestSetDetailResultTable();
$data_array = $result_obj->getDetailReportByUser($user_id, $test_id);
if($data_array['status'] == 1) {
echo $this->successMessage('successfully Executed',$data_array['record']);
} else {
echo $this->failMessage($data_array['error'],$data_array['message']);
}
exit;
}
Model code:
public function getDetailReportByUser($user_id,$test_id) {
$data_array = Array();
$subject_array = Array();
$answer_array = Array();
$topper_array = Array();
$percentile_array = Array();
$max_marks = 0;
$perc = 0;
$hrs = 0;
$mint = 0;
$sec = 0;
$query = new AppQuery();
$query->callProcedure('getSummaryResult',array($test_id,$user_id));
$row_list = $this->loadRowList($query);
if(count($row_list) > 0) {
$max_marks = $row_list[0]->maximum_marks;
$perc = $row_list[0]->percentage;
$query->callProcedure('getCompletedTestTime',array($user_id,$test_id));
$row_time = $this->loadRowList($query);
$query->callProcedure('getAllUserPerTest',array($test_id));
$row_user = $this->loadRowList($query);
if(count($row_time)> 0 && count($row_user) > 0) {
foreach ($row_list as $list) {
$item['test_name'] = $list->test_name;
$item['total_question'] = $list->total_question;
$item['right_answer'] = $list->right_answer;
$item['wrong_answer'] = $list->wrong_answer;
$item['question_attempted'] = $list->question_attempted;
$item['question_not_attempted'] = $list->question_not_attempted;
$item['positive_marks'] = $list->positive_marks;
$item['negative_marks'] = $list->negative_marks;
$item['obtaine'] = $list->obtaine;
$item['maximum_test_time'] = $list->maximum_test_time;
$item['maximum_marks'] = $list->maximum_marks;
$item['test_date'] = $list->test_date;
$number = floatval($list->obtaine)* 100 / intval($list->maximum_marks);
$item['percentage'] = number_format($number, 2, '.', ''); // upto 2 decimal places
$data_array['detail'] = $item;
}
$tmp = Array();
$hrs = $row_time[0]->spent_hours;
$mint = $row_time[0]->spent_minute;
$sec = $row_time[0]->spent_second;
$completed_minute = $row_time[0]->compeleted_minute;
$completed_second = $row_time[0]->compeleted_second;
if($completed_second < 0) {
$completed_second = -1 * $completed_second; // only removing - sign
}
$tmp = $this->calculateTime($hrs, $mint, $sec);
$tmp['compeleted_minute'] = $completed_minute;
$tmp['compeleted_second'] = $completed_second;
$data_array['time'] = $tmp;
foreach ($row_user as $list) {
$tem['total_user'] = $list->total_user;
$data_array['users'] = $tem;
}
// Now get The subject wise Result
$temp = Array();
$query->callProcedure('getTestResult',array($test_id,$user_id));
$subject_result = $this->loadRowList($query);
foreach ($subject_result as $res) {
$temp['subject_name']= $res->subject_name;
$temp['marks_obtained'] = $res->obtaine;
$temp['total_question'] = $res->total_question;
$temp['question_attempted'] = $res->question_attempted;
$temp['wrong_answer'] = $res->wrong_answer;
// $temp['total_spent_hours'] = $res->total_spent_hours;
// $temp['total_spent_minute'] = $res->total_spent_minute;
// $temp['total_spent_second'] = $res->total_spent_second;
$time_arr2 = $this->calculateTime($res->total_spent_hours, $res->total_spent_minute, $res->total_spent_second);
$temp['total_spent_hours'] = $time_arr2['hours'];
$temp['total_spent_minute'] = $time_arr2['minute'];;
$temp['total_spent_second'] = $time_arr2['second'];
$temp['max_marks'] = intval($res->total_question) * intval($res->positive_marks);
$subject_array[] = $temp;
}
$data_array['subject_result'] = $subject_array;
//>>>>>>>>>>> Now get Answer of Question with Time spent>>>>>>>>>>
$temp = Array();
$query->callProcedure('getAnswerwithTime',array($test_id,$user_id));
$answer_list = $this->loadRowList($query);
foreach ($answer_list as $res) {
$temp['question']= utf8_encode($res->question);
$temp['user_answer']= $res->user_answer;
$temp['correct_answer'] = $res->correct_answer;
$temp['spent_hours'] = $res->spent_hours;
$temp['spent_minute'] = $res->spent_minute;
$temp['spent_second'] = $res->spent_second;
$temp['obtaine'] = $res->obtaine;
$answer_array[] = $temp;
}
$data_array['answer_with_time'] = $answer_array;
/*>>>>>>>>End>>>>>>>>>>>>>*/
/*>>>>>>>>>>>>>>For Topper result for Comparing>>>>>>>>>>>>>>>>*/
$temp = Array();
$query->callProcedure('getTopperResult',array($test_id));
$top_arr = $this->loadRowList($query);
foreach ($top_arr as $top) {
$temp['user_name'] = $top->user_name;
$temp['test_name'] = $top->test_name;
$temp['total_question'] = $top->total_question;
$temp['right_answer'] = $top->right_answer;
$temp['wrong_answer'] = $top->wrong_answer;
$temp['question_attempted'] = $top->question_attempted;
$temp['question_not_attempted'] = $top->question_not_attempted;
$temp['positive_marks'] = $top->positive_marks;
$temp['negative_marks'] = $top->negative_marks;
$temp['maximum_marks'] = $top->maximum_marks;
$temp['obtaine'] = $top->obtaine;
$temp['percentage'] = $top->percentage;
$temp['maximum_test_time'] = $top->maximum_test_time;
$temp['test_date'] = $top->test_date;
$timer = $this->calculateTime( $top->spent_hours, $top->spent_minute, $top->spent_second);
$temp['spent_hours'] = $timer['hours'];
$temp['spent_minute'] = $timer['minute'];
$temp['spent_second'] = $timer['second'];
$temp['completed_minute'] = $top->completed_minute;
$sec_var = $top->completed_second;
if($sec_var < 0) {
$sec_var = -1 * $sec_var;
}
$temp['completed_second'] = $sec_var;
$percentile = $this->getPercentileRank($test_id,$top->percentage,$top->maximum_marks);
$temp['percentile'] = $percentile; // percentile
// $temp['rank'] = intval($percentile); // Rank
$topper_array[] = $temp;
}
//>>>>>>>>>>>>>>>>>> topper array contain Topper Percentile,now we need to get Rank according to Percentile
$topper_array = $this->rank($topper_array);
$data_array['toppers_result'] = $topper_array;
/*>>>>>>>>>>>>>>For Topper Result>>>>>>>>>>>>>>>>*/
/*>>>>>>>>>>>>>>For Login user Percentile>>>>>>>>>>>>>>>>*/
$percentile = $this->getPercentileRank($test_id, $perc, $max_marks);
$percentile_array = $this->loginUserRank($topper_array, $percentile);
$data_array['percentile'] = $percentile_array;
/*>>>>>>>>>>>>>>For Login user Percentile End>>>>>>>>>>>>>>>>*/
/*>>>>>>>>>Get subject Wise Time of Toppers >>>>>>>>>>>>>*/
$subject_wise_time = $this->getSubjectWiseTopperTime($test_id);
$data_array['subject_wise_topper_time'] = $subject_wise_time;
/*>>>>>>>>>Get subject Wise Time of Toppers End >>>>>>>>>>>>>*/
/*>>>>>>>>>Get Answer with Time of Toppers >>>>>>>>>>>>>*/
$topper_answer_with_time = $this->topperAnswerTime($test_id);
$data_array['topper_answer_with_time'] = $topper_answer_with_time;
/*>>>>>>>>>Get Answer with Time of Toppers Ends >>>>>>>>>>>>>*/
return $this->modelMessage(1,'non','success',$data_array); exit;
} else {
return $this->modelMessage($this->getStatus(),$this->getError(),$this->getMessage()); exit;
}
} else {
return $this->modelMessage($this->getStatus(),$this->getError(),$this->getMessage()); exit;
}
}
I'm trying to debug this code but I don't know what am I missing here.How can this take 15 secs of time to return response back? Have I done something wrong?
When you debug than calculate the needed times with microtime(true), my guess are the DB querys for instance:
$start=microtime(true);
$answer_list = $this->loadRowList($query);
$stop=microtime(true);
$neededTime=$stop-$start;
echo "Time for answer_list $neededTime s for query $query";
Than you see what need to longest time. Than look on your query an look on your database schema. In most cases you can solve that issue by adding some indices on your db table. You can "debug" the query with explain on sql level, this will show you if you use an index.
First of all I'm wondering if this is even possible in Laravel?
I have this code:
$master_array = $_POST['master_search_array'];
$count = count($master_array);
$master_string = '';
for($i=0; $i<$count; $i++) {
if($master_array[$i] == "Dining"){
$master_string .= "where('dining', 'dining')";
}
if($master_array[$i] == "Party"){
$master_string .= "where('party','party')";
}
....ETC you get the point
}
$tours = DB::table('tours')->$master_string->get();
return $tours;
So at the end I should get something like this:
$tours = DB::table('tours')->where('dining', 'dining)->where('party','party')->get();
How can I do this in laravel, it gives me an error, no matter if I pass it as $master_string or {{$master_string}}.
There is no need for master string. Just use the query builder how it's meant to be used...
$master_array = $_POST['master_search_array'];
$count = count($master_array);
$query = DB::table('tours');
for($i=0; $i<$count; $i++) {
if($master_array[$i] == "Dining"){
$query->where('dining', 'dining');
}
if($master_array[$i] == "Party"){
$query->where('party', 'party');
}
}
$tours = $query->get();
return $tours;
Use the ability to add wheres to the query along the way.
DB::table('tour')->where(function($query) use ($master_array)
{
foreach($master_array as $k => $v) {
if($v == "Dining"){
$query->where('dining','dining');
}
if($v == "Party"){
$query->where('party','party');
}
}
})
->get();
I'm currently experiencing issues where array_push() is not working. I have ensured the arrays are directly accessible and declared correctly. Yet I'm still receiving these warnings and the values are not being pushed onto the array.
Here is my code:
include('../connstr.inc');
$email=$_REQUEST["email"];
$datafile=$_REQUEST["datafile"];
$email_safe=preg_replace("/[^a-zA-Z]/","_",$email);
$path="../uploaded_data";
$xml = simplexml_load_file("{$path}/{$email_safe}/{$datafile}.xml");
// Retreive data details for specified activity
$lapCount = $xml->Activities->Activity->Lap->count();
// Lap Variables
$totalTime = array(); $distance = array(); $maxSpeed = array();
$calories = array(); $intensity = array(); $trigMethod = array();
$avgSpeed = array();
// Convert filename to DateTime format
$datafile = convertID($datafile);
$datafile = date('Y-m-d H:i:s', strtotime($datafile));
// Variables for accurate distance calculations
$polarDistance = true;
$lapID;
$totalLapDistance;
$firstPoint = array();
$secondPoint = array();
// Collect details for each lap
for($x = 0; $x < $lapCount; $x++) {
$totalLapDistance = 0;
$lapNumber = $x+1;
$totalTime[$x] = $xml->Activities->Activity->Lap[$x]->TotalTimeSeconds;
$distance[$x] = $xml->Activities->Activity->Lap[$x]->DistanceMeters;
$maxSpeed[$x] = $xml->Activities->Activity->Lap[$x]->MaximumSpeed;
$calories[$x] = $xml->Activities->Activity->Lap[$x]->Calories;
$intensity[$x] = $xml->Activities->Activity->Lap[$x]->Intensity;
$trigMethod[$x] = $xml->Activities->Activity->Lap[$x]->TriggerMethod;
$avgSpeed[$x] = $xml->Activities->Activity->Lap[$x]->Extensions->LX->AvgSpeed;
// Store activity details into the 'detail' table
$sqlLap = "INSERT INTO lap (lapDate,lapNumber,TotalTime,distance,maxSpeed,avgSpeed,calories,intensity,trigMethod) VALUES (\"$datafile\",\"$lapNumber\",\"$totalTime[$x]\",\"$distance[$x]\",\"$maxSpeed[$x]\",\"$avgSpeed[$x]\",\"$calories[$x]\",\"$intensity[$x]\",\"$trigMethod[$x]\")";
$runLap = mysql_query($sqlLap) or die("unable to complete INSERT action:$sql:".mysql_error());
// Trackpoint variables
$altitude = array(); $tDistance = array(); $latitude = array();
$longitude = array(); $speed = array(); $pointTime = array();
// Retreive lapID
$lapID = getLapID();
// Find how many tracks exist for specified lap
$trackCount = $xml->Activities->Activity->Lap[$x]->Track->count();
$trackpointTotalCount = 1;
for($t = 0; $t < $trackCount; $t++) {
// Find out how many trackpoints exist for each track
$trackpointCount = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint->count();
// Collect details for each specificied track point
for($tp = 0; $tp < $trackpointCount; $tp++) {
$altitude[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->AltitudeMeters;
$tDistance[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->DistanceMeters;
$pointTime[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->Time;
$latitude[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->Position->LatitudeDegrees;
$longitude[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->Position->LongitudeDegrees;
$speed[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->Extensions->TPX->Speed;
// Check Track point
if(checkTP($altitude[$tp], $tDistance[$tp], $latitude[$tp], $longitude[$tp], $speed[$tp])) {
// Check if accurate distance should be calculated
if($polarDistance) {
$aa = $latitude[$tp];
$bb = $longitude[$tp];
$cc = $altitude[$tp];
if($tp == 0) {
array_push($firstPoint, $aa, $bb, $cc);
} else if($tp != 0) {
array_push($secondPoint, $aa, $bb, $cc);
}
printArray($firstPoint);
printArray($secondPoint);
// Add distance between trackpoints to total lap distance
$totalLapDistance += calcDistance($firstPoint, $secondPoint);
}
// Insert current trackpoint data into 'trackpoint' table
$sqlTC = "INSERT INTO trackpoint (tpDate,tpNumber,altitude,distance,latitude,longitude,speed,pointTime) VALUES (\"$datafile\",\"$trackpointTotalCount\",\"$altitude[$tp]\",\"$tDistance[$tp]\",\"$latitude[$tp]\",\"$longitude[$tp]\",\"$speed[$tp]\",\"$pointTime[$tp]\")";
$runTC = mysql_query($sqlTC) or die("unable to complete INSERT action:$sql:".mysql_error());
}
$trackpointTotalCount++;
if($polarDistance) {
if($tp != 0) {
unset($firstPoint);
$firstPoint = &$secondPoint;
unset($secondPoint);
}
}
}
}
if($polarDistance) {
if($tp != 0) {
// Update lap with more accurate distance
echo $totalLapDistance . '<br />';
$sqlUlap = "UPDATE lap SET accDistance='$totalLapDistance' WHERE lapID = '$lapID' ";
$runUlap = mysql_query($sqlUlap) or die("unable to complete UPDATE action:$sql:".mysql_error());
}
}
}
I didn't include all of the code below as there is quite a lot and I very much doubt it's relevant.
The warnings themselves only appear when trying to push a variable onto $secondPoint:
array_push($secondPoint, $aa, $bb, $cc);
However values are not being pushed onto either of the variables ($firstPoint, $secondPoint)
As a test I did echo $aa,bb and $cc and they did contain correct values.
Anybody have an idea of what I'm doing wrong?
EDIT: I have showed more of the code as I do use these arrays later, however this should not affect how the values are initially pushed? Below is some code which may affect it, namely the assign by reference?
if($polarDistance) {
if($tp != 0) {
unset($firstPoint);
$firstPoint = &$secondPoint;
unset($secondPoint);
}
}
That unset($secondPoint) will probably do it.
Try this instead:
if($polarDistance) {
if($tp != 0) {
$firstPoint = $secondPoint;
$secondPoint = array();
}
}