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
Related
i want to count my score from option a/b/c that inputted from a form. for each input given, value from a =1,b=2,c=3 ,after count i want to save the result in score variable
in my controller
public function score($id) {
$user_login = Auth::user()->id;
$answers = Answer::select('user_answer')->where('jenis_quiz_id','=',$id)->where('user_id','=',$user_login)->get();
static $a = 0;
static $b = 0;
static $c = 0;
static $score = 0;
if($answers->count()) {
foreach ($answers as $answer) {
if ($answer->user_answer == '1') {
$a++;
} else if($answer->user_answer == '2') {
$b++;
} elseif($answer->user_answer == '3') {
$c++;
}
}
}
$score = $a+$b+$c;
$returnScore = $score;
$a = null;
$b = null;
$c = null;
$score = null;
return $returnScore;
}
public function getShowResultOfQuiz($id) {
$categoryquiz = JenisQuiz::findOrFail($id);
$user = Auth::user()->id;
$score= $this->score($id);
$kelas = Auth::user()->kelas;
$instansi = Auth::user()->instansi;
History::create([
'user_id'=>$user,
'jenis_quiz_id'=>$id,
'score'=> $score,
'kelas' => $kelas,
'instansi' => $instansi
]);
// $time_taken = date("H:i:s", strtotime(Answer::whereJenisQuizId($id)->orderBy('id', 'desc')->first()->time_taken));
switch ($id) {
case '1':
return view('quiz1',compact('score','categoryquiz'));
case '2':
return view('quiz2',compact('score','categoryquiz'));
case '3':
return view('quiz3',compact('score','categoryquiz'));
}
}
i want to reset a,b,c,and score variables every input submitted,and the problem is score always added from previous submitted answer instead of reset it before calculating the score again, help me , thanks
I know that this question in the tittle is asked WAYY too much in here, and I went thru most of them but still cant find a solution for my code.
function calculatingWages($project_id){
$start_date = '2017-05-01';
$end_date = '2017-12-31';
$project = Project::find($project_id);
$users = $project->users()->get();
$sumWage=0;
foreach ($users as $user){
$timesheetHours = $user->timesheets()->whereBetween('timesheets.date',[$start_date,$end_date])->sum('hours');
$wages = UserWage::whereBetween('start_date',[ $start_date,$end_date])->whereBetween('end_date',[ $start_date,$end_date])->get();
foreach ($wages as $wage){
$value = $wage->value;
$currency = $wage->currency;
$sumWage = extractMonthsAndCalculate($value,$currency, $timesheetHours, $start_date, $end_date);
}
return $sumWage;
}
}
function extractMonthsAndCalculate($value,$currency, $timesheetHours, $start_date, $end_date){
$start = Carbon::createFromFormat('Y-m-d',$start_date)->month;
$end = Carbon::createFromFormat('Y-m-d',$end_date)->month;
$diffOfMonths = $end - $start;
$sumWage = 0;
for ($i = $start; $i <= $diffOfMonths; $i++) {
$wageYear = Carbon::createFromFormat('Y-m-d',$start_date)->year;
$wageDay = Carbon::createFromDate($wageYear,$i,'01')->lastOfMonth()->toDateString();
$test = convertingALL($value,$currency,$timesheetHours,$wageDay);
}
return $sumWage;
}
function convertingALL($value, $currency, $timesheetHours, $date)
{
$currencyObj = Exchange::where('date',$date)->get()->first();
$currencyDate = $currencyObj->date;
$hourlyWage = 0;
$sumWage = 0;
if($currencyDate == $date) {
$dollar = $currencyObj->dollar_lek;
$euro = $currencyObj->euro_lek;
if ($currency == 'ALL') {
$sumWage = $value;
} elseif ($currency == 'USD') {
$sumWage = ($hourlyWage *$timesheetHours) * $dollar;
} else {
$sumWage = ($hourlyWage *$timesheetHours)* $euro;
}
}else{
$euro = 140;
$dollar = 136.4;
if ($currency == 'ALL') {
$sumWage = $value;
} elseif ($currency == 'USD') {
$sumWage = $value * $dollar;
} else {
$sumWage = $value * $euro;
}
}
return $sumWage;
}
it says that it cant get the property of a non object in line 468
this is line 467-468:
$currencyObj = Exchange::where('date',$date)->get()->first();
$currencyDate = $currencyObj->date;
when I dd $currencyDate it prints the date of it, tried to parse it using carbon but still same thing, where am I messing up?
You need to tell Eloquent that the date field contains a date (even though it seems obvious).
Docs: https://laravel.com/docs/5.4/eloquent-mutators#date-mutators
In your Exchange model you should have
class Exchange extends Model {
protected $dates = [ 'date' ];
On an unrelated note, ->get()->first() will pull every single result back from the database, then chuck all but one of them away. If you just call ->first() then you'll only get one result from the database; same end result but better for performance.
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.
The sales notifications is not working because this line amountArray[$idproduct] += $amount; is returning me offset. I don't know how to fix it.
My full function is this:
function saveAllSaleDetails($idsale, $sale) {
$this->conexion->startTransaction();
$amountArray = [];
try {
foreach ($sale as $detail):
$idproduct = $detail['id'];
$amount = $detail['amount'];
$price = $detail['price'];
$subtotal = $detail['subtotal'];
$iduser = 1;
$this->saveSaleDetail($idsale, $idproduct, $amount, $price, $subtotal, $iduser);
$amountArray[$idproduct] += $amount;
$stock = $this->product->getProductStock($idproduct);
$stock = $stock[0][0] - $amountArray[$idproduct];
if ($stock <= 20) {
$product = $this->product->getProductById($idproduct);
$message = $product[0][1]." stock is bellow 20.";
notification::add($message, $idproduct, 'warning', 'product.php');
}
endforeach;
$this->conexion->commit();
$this->conexion->cerrar();
return true;
} catch (Exception $e) {
$this->conexion->rollback();
$this->conexion->cerrar();
var_dump($e->getMessage());
return false;
}
}
The problem is because of this line,
$amountArray[$idproduct] += $amount;
The above statement can be expanded as
$amountArray[$idproduct] = $amountArray[$idproduct] + $amount;
Initially during the first iteration of foreach loop, $amountArray[1] and $amountArray[2] are not set, and hence you're getting these undefined offset error.
So instead of
$amountArray[$idproduct] += $amount;
Do this:
$amountArray[$idproduct] = isset($amountArray[$idproduct]) ? $amountArray[$idproduct] + $amount : $amount;
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"