Laravel getQueryLog show line query is executed - laravel

as title says I wonder if there is an way to get the getQueryLog function to show line of the query.
var_dump(DB::getQueryLog())

You can't do it with getQueryLog(), but you can listen to queries, generate a backtrace and finally extract line number:
// routes.php
Event::listen('illuminate.query', function($query,$binding,$time,$connections){
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
foreach ($backtrace as $trace) {
if(array_key_exists('file',$trace) && array_key_exists('line',$trace)){
if( strpos($trace['file'],base_path().'/app') !== false ){
var_dump(array(
'query' => $query
,'binding' => $binding
,'time' => $time
,'connection' => $connections
,'file' => $trace['file']
,'line' => $trace['line']
));
break;
}
}
}
});

Related

Laravel ErrorException Undefined variable in my public function

I ran into the error:
ErrorException Undefined variable: pesan
I have gone through similar problems solved here but none of the solutions have worked for me.
The error is thrown from my RegisterController at bottom of the line. At the pesan
I use laravel 8
Here is my controller code:
` public function simpan_rm(Request $request)
{
$this->validate($request, [
'idpasien' => 'required|numeric|digits_between:1,4',
'keluhan_utama' => 'required|max:40',
'anamnesis' => 'required|max:1000',
'px_fisik' => 'max:1000',
'diagnosis' => 'max:40',
'dokter' => 'required',
]);
// Decoding array input pemeriksaan lab
if (isset($request->lab))
{
if (has_dupes(array_column($request->lab,'id'))){
$errors = new MessageBag(['lab'=>['Lab yang sama tidak boleh dimasukan berulang']]);
return back()->withErrors($errors);
}
$this->validate($request, [
'lab.*.hasil' => 'required|numeric|digits_between:1,4',
]);
$lab_id = decode('lab','id',$request->lab);
$lab_hasil = decode('lab','hasil',$request->lab);
}
else {
$lab_id ="";
$lab_hasil ="";
}
// Decoding array input resep
if (isset($request->resep))
{
if (has_dupes(array_column($request->resep,'id'))){
$errors = new MessageBag(['resep'=>['resep yang sama tidak boleh dimasukan berulang']]);
return back()->withErrors($errors);
}
$this->validate($request, [
'resep.*.jumlah' => 'required|numeric|digits_between:1,3',
'resep.*.aturan' => 'required',
]);
$resep_id = decode('resep','id',$request->resep);
$resep_jumlah = decode('resep','jumlah',$request->resep);
$resep_dosis = decode('resep','aturan',$request->resep);
}
else {
$resep_id = "";
$resep_jumlah = "";
$resep_dosis = "";
}
$newresep = array();
$oldresep=array();
if (is_array($request) || is_object($newresep))
{
foreach ($request->resep as $resep){
$newresep[$resep['id']] = $resep['jumlah'];
}
}
if (empty($oldresep)) {
$resultanresep = resultan_resep($oldresep,$newresep);
}
else {$resultanresep=$newresep;}
$errors = validasi_stok($resultanresep);
if ($errors !== NULL) {
return back()->withErrors($errors);
}
foreach ($resultanresep as $key => $value) {
$perintah=kurangi_stok($key,$value);
if ($perintah === false) { $habis = array_push($habis,$key); }
}
DB::table('rm')->insert([
'idpasien' => $request->idpasien,
'ku' => $request->keluhan_utama,
'anamnesis' => $request->anamnesis,
'pxfisik' => $request->px_fisik,
'lab' => $lab_id,
'hasil' => $lab_hasil,
'diagnosis' => $request->diagnosis,
'resep' => $resep_id,
'jumlah' => $resep_jumlah,
'aturan' => $resep_dosis,
'dokter' => $request->dokter,
'created_time' => Carbon::now(),
'updated_time' => Carbon::now(),
]);
$ids= DB::table('rm')->latest('created_time')->first();
switch($request->simpan) {
case 'simpan_edit':
$buka=route('rm.edit',$ids->id);
$pesan='Data Rekam Medis berhasil disimpan!';
break;
case 'simpan_baru':
$buka=route('rm.tambah.id',$request->idpasien);;
$pesan='Data Rekam Medis berhasil disimpan!';
break;
}
return redirect('buka')->with('pesan',$pesan);
}`
Unfortunately i've modified return redirect('buka')->with('pesan',$pesan); but didn't work for me.
Please help
$pesan is defined in 2 cases of your switch statement.
So what happens when $request->simpan is neither equal to simpan_edit or simpan_baru ?
In this case (wich is not handled in your code), $pesan will be undefined and an error will throw.
A good practice using switch statements is to add a default: case wich will match any other values that you didn't explicitely set a case: for.
Example :
switch($request->simpan) {
case 'simpan_edit':
$buka=route('rm.edit',$ids->id);
$pesan='Data Rekam Medis berhasil disimpan!';
break;
case 'simpan_baru':
$buka=route('rm.tambah.id',$request->idpasien);;
$pesan='Data Rekam Medis berhasil disimpan!';
break;
default:
// you may set a default value for `$pesan` here
$pesan=null;
}
it seems that the error is related to the $pesan variable, according to the code you've provided, $pesan is not defined anywhere in the controller, which is why you're receiving the Error Exception Undefined variable : pesan error
for resolve this issue, you should either define the $pesan variable or remove any reference to it in the code
if $pesan is meant to store some message, it should be defined and assigned a value before being used

Laravel - How to update table multiple rows at once

I have this variable called $projectFieldOptions and it's output is like this:
https://prnt.sc/7HtxrfTy9HiI.
Now, In the Controller I need to update this. What I am doing this, first delete all the existing rows based on id_feed and id_project and then loop through this variable $projectFieldOptions and insert it. Like this:
if( $request->feed_type !== 'scrape' ) {
$delete_mapping = DB::connection($db_name)->table($db_name . '.feed_mappings')
->where('id_feed', '=', $id_feed)
->where('id_project', '=', $token)
->delete();
}
// now insert
$field_mapping = true;
if( $request->feed_type !== 'scrape' ) {
if( count($projectFieldOptions) ) {
foreach ($projectFieldOptions as $mapping) {
$data[] = [
'id_feed' => $id_feed,
'id_project' => $token,
'import_field_slug' => $mapping['value'],
'internal_field_slug' => $mapping['custom'] ? $mapping['custom_field'] : $mapping['text'],
'custom_field' => $mapping['custom'],
'updates' => $mapping['updates'],
'removes' => $mapping['removes'],
'import' => 1,
'date_add' => now(),
'date_upd' => now()
];
}
} else {
$data = [];
}
$field_mapping = DB::connection($db_name)->table($db_name . ".feed_mappings")->insert($data);
}
Now, I don't want to delete existing rows instead I want to update those rows based on the id_feed_mappings. Can you tell how can I do this?
Check if this would work, to update based on id_feed_mappings value, you can use the ->where('id_feed_mappings', '=' ,'a value or variable') before ->update($data)
if( $request->feed_type !== 'scrape' ) {
// try using update instead of insert
$field_mapping = true;
if( $request->feed_type !== 'scrape' ) {
if( count($projectFieldOptions) ) {
foreach ($projectFieldOptions as $mapping) {
$data[] = [
'id_feed' => $id_feed,
'id_project' => $token,
'import_field_slug' => $mapping['value'],
'internal_field_slug' => $mapping['custom'] ? $mapping['custom_field'] : $mapping['text'],
'custom_field' => $mapping['custom'],
'updates' => $mapping['updates'],
'removes' => $mapping['removes'],
'import' => 1,
'date_add' => now(),
'date_upd' => now()
];
}
} else {
$data = [];
}
$field_mapping = DB::connection($db_name)->table($db_name . ".feed_mappings")->update($data);
}

Laravel : array_push not working in collection->each() iterator

I have grouped collection and I iterate it using each() function.Inside the each function I want to add element to some array.But it is not working.Any idea?
$dataSet1 = [];
$appointments = [
['department' => 'finance', 'product' => 'Chair'],
['department' => 'marketing', 'product' => 'Bookcase'],
['department' => 'finance', 'product' => 'Desk'],
];
$groupData = collect($appointments)->groupBy('department');
$groupData->each(function ($item, $key) {
Log::info($key); //Show correct output in log
array_push($dataSet1, $key); //ERROR
array_push($dataSet1, 'A');//ERROR
});
Laravel version : 8.35.1
You need to pass the array to the function with use:
$groupData->each(function ($item, $key) use (&$dataSet1) {
Log::info($key); //Show correct output in log
array_push($dataSet1, $key); //ERROR
array_push($dataSet1, 'A');//ERROR
});
Pass-by-reference (&) is needed as long as $dataSet1 is not an object instance.

Laravel 8 update pivot table if nothing was edited in the form

I have a pivot table with extra fields ('tugas_1'-'tugas_10') with enum type, the point of this update is to modify those fields.
the problem is if the user open the modal form and then submit it with no changes, the pages goes blank but if I change one or more of the fields, it works. this happens if I only use the updateExistingPivot method so I solve this by checking first if the old value is the same as the request form value, then it will run the sync method. but is there any other way to solve this? and my code looks like a mess, I appreciate it if you know how to make it simple
this is my edit method on the controller.
public function edit(Request $request, $id_angkatan, $id_semester, $id) {
$peserta = Peserta::where('id', $id)->first();
$tugas = $peserta->semestertugas()->where('semester_id', $id_semester)->first();
if($tugas->pivot->tugas_1 == $request->tugas_1 &&
$tugas->pivot->tugas_2 == $request->tugas_2 &&
$tugas->pivot->tugas_3 == $request->tugas_3 &&
$tugas->pivot->tugas_4 == $request->tugas_4 &&
$tugas->pivot->tugas_5 == $request->tugas_5 &&
$tugas->pivot->tugas_6 == $request->tugas_6 &&
$tugas->pivot->tugas_7 == $request->tugas_7 &&
$tugas->pivot->tugas_8 == $request->tugas_8 &&
$tugas->pivot->tugas_9 == $request->tugas_9 &&
$tugas->pivot->tugas_10 == $request->tugas_10){
$query = $peserta->semestertugas()->sync($id_semester,
[
'tugas_1' => $tugas->pivot->tugas_1 = $request->tugas_1,
'tugas_2' => $tugas->pivot->tugas_2 = $request->tugas_2,
'tugas_3' => $tugas->pivot->tugas_3 = $request->tugas_3,
'tugas_4' => $tugas->pivot->tugas_4 = $request->tugas_4,
'tugas_5' => $tugas->pivot->tugas_5 = $request->tugas_5,
'tugas_6' => $tugas->pivot->tugas_6 = $request->tugas_6,
'tugas_7' => $tugas->pivot->tugas_7 = $request->tugas_7,
'tugas_8' => $tugas->pivot->tugas_8 = $request->tugas_8,
'tugas_9' => $tugas->pivot->tugas_9 = $request->tugas_9,
'tugas_10' => $tugas->pivot->tugas_10 = $request->tugas_10
]);
if ($query){
return back()->with('pesan', 'Tugas peserta berhasil diedit');
}
}
else{
$query = $peserta->semestertugas()->updateExistingPivot($id_semester,
[
'tugas_1' => $tugas->pivot->tugas_1 = $request->tugas_1,
'tugas_2' => $tugas->pivot->tugas_2 = $request->tugas_2,
'tugas_3' => $tugas->pivot->tugas_3 = $request->tugas_3,
'tugas_4' => $tugas->pivot->tugas_4 = $request->tugas_4,
'tugas_5' => $tugas->pivot->tugas_5 = $request->tugas_5,
'tugas_6' => $tugas->pivot->tugas_6 = $request->tugas_6,
'tugas_7' => $tugas->pivot->tugas_7 = $request->tugas_7,
'tugas_8' => $tugas->pivot->tugas_8 = $request->tugas_8,
'tugas_9' => $tugas->pivot->tugas_9 = $request->tugas_9,
'tugas_10' => $tugas->pivot->tugas_10 = $request->tugas_10
]);
if ($query){
return back()->with('pesan', 'Tugas peserta berhasil diedit');
}
}
}
this is the edit form view
this is the table view
this is the pivot table
I hope you can understand my explanation!
There is no need to update if there is no changes. Maybe what you're after is the sync whithout detaching
public function edit(Request $request, $id_angkatan, $id_semester, $id)
{
$peserta = Peserta::where('id', $id)->first();
$query = $peserta->semestertugas()->syncWithoutDetaching([$id_semester => [
'tugas_1' => $request->tugas_1,
'tugas_2' => $request->tugas_2,
'tugas_3' => $request->tugas_3,
'tugas_4' => $request->tugas_4,
'tugas_5' => $request->tugas_5,
'tugas_6' => $request->tugas_6,
'tugas_7' => $request->tugas_7,
'tugas_8' => $request->tugas_8,
'tugas_9' => $request->tugas_9,
'tugas_10' => $request->tugas_10,
]]);
if ($query) {
return back()->with('pesan', 'Tugas peserta berhasil diedit');
}
}

saving number field with a value of zero in Laravel 5.5

I have a form that accepts delivery of products which I noticed if I enter 0 in the quantity field it doesn't save in the database even if I add data in the calendar or in Notes field.
I already commented out the \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,iin kernel.php still doesn't work.
how can I forced laravel to save my data even if I want to put 0 in quantity? thanks in advance!
update
public function store(Request $request)
{
$input = $request->all();
$items = [];
for ($i = 0; $i <= count($input['order_id']); $i++) {
if (empty($input['stock_in_qty'][$i]) || !is_numeric($input['stock_in_qty'][$i])) continue;
$acceptItem = [
'order_id' => $input['order_id'][$i],
'product_id' => $input['product_id'][$i],
'order_item_id' => $input['order_item_id'][$i],
'delivery_date' => $input['delivery_date'][$i],
'company_id' => $input['company_id'][$i],
// 'stock_in_qty' => intval($input['stock_in_qty'])[$i],
'stock_in_qty' => $input['stock_in_qty'][$i],
// 'stock_out_qty' => $input['stock_out_qty'][$i],
// 'transfer_to' => $input['transfer_to'][$i],
'delivery_note' => $input['delivery_note'][$i],
'user_id' => $input['user_id'][$i],
];
array_push($items, Warehouse1stocks::create($acceptItem));
$stockSummary = Warehouse1StockSummaries::firstOrCreate(
['product_id' => $input['product_id'][$i]],
['qty_in' => $input['stock_in_qty'][$i],
'qty_out' => null,
]);
if (!$stockSummary->wasRecentlyCreated) {
$stockSummary->increment('qty_in', $input['stock_in_qty'][$i]);
}
}
if ($input['rd'] == $input['stock_in_qty'] || $input['rd'] == 0) {
$order_idAcceptedItem = $acceptItem['order_id'];
$setStatus = \App\Orders::where('id', '=', $order_idAcceptedItem)->first();
if ($setStatus) {
$setStatus->status_id = 4;
}
$setStatus->save();
} else {
$order_idAcceptedItem = $acceptItem['order_id'];
$setStatus = \App\Orders::where('id', '=', $order_idAcceptedItem)->first();
if ($setStatus) {
$setStatus->status_id = 3;
}
$setStatus->save();
}
return redirect()->route('orders.index');
}
empty() will return true with 0 or '0' which will mean that if you try to change the quantity to 0 the for loop will just continue on to the next loop. If you need to check if the value exists you can instead use isset().
Changing your first if statement to the following should be all you need:
if(!isset($input['stock_in_qty'][$i]) || !is_numeric($input['stock_in_qty'][$i])) continue;

Resources