I am trying to get collection of data from RestFul api, when $response variable return data everything is well, but if not, i am faced a problem, this is my code:
public function showAsStage($id)
{
try {
$notis = Notification::with('stage')->orderBy('created_at', 'desc')
->where('stage_id', $id)
->get();
if(!$notis->isEmpty()){
foreach($notis as $noti){
$json = $noti->file ? json_decode($noti->file) : '';
$file = $json ? (string)$json[0]->download_link : '';
$response[] = [
'id' => $noti->id ? $noti->id : '',
'body' => $noti->body ? $noti->body : '',
'stage' => $noti->stage->stage ? $noti->stage->stage : '',
'time' => $noti->created_at ? $noti->created_at : '',
'course' => "عام",
'image' => $noti->file ?'http://172.18.23.41:8000/storage/'.$file : null
];
}
}
}catch(\Exception $e){
return $this->sendError('Server Error.', $e->getMessage());
}finally{
return $this->sendResponse($response, 'Successfully fetch noti meta data');
}
}
when there is no data :
"Undefined variable: response"
This happend becuase You haven't assign your variable before your foreach loop ($reponse=[]) .... So, inorder to solve this problem make an empty array before your try scope and inside your loop add your data to your array with array_push()
Related
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
I am getting a issue while fetching array data in Laravel 7 here is my code
https://i.stack.imgur.com/IZbg6.png
and the result is : https://i.stack.imgur.com/ByKaV.png
It is fetching only one array data. I don't know where i am missing.
If anybody know the error, please help me to solve this issue.
Below is my code ======================================
$cat_id = $category->id;
$location = null;
$sites = \DB::select( 'SELECT id FROM sites WHERE category_id = ?', [ $category->id ]);
$all = [ ];
foreach( $sites as $s ) {
$all[ ] = $s->id;
}
$sites = $all;
$all_cat_id = implode(',', array_map('intval', $sites));
// echo "<pre>";
// print($all_cat_id);
// die();
$sites = Sites::withCount('reviews')->orderBy('reviews_count', 'desc')->where('id', [$all_cat_id])->paginate(10);
return view('browse-category', [ 'activeNav' => 'home',
'reviews' => $reviews,
'sites' => $sites,
'category' => $category,
'all_categories' => $all_categories,
'location' => $location
]);
$sites = Sites::withCount('reviews')->orderBy('reviews_count', 'desc')->whereIn('id', [$all_cat_id])->paginate(10);
You need to use whereIn() instead of where()
whereIn() checks column against array.
I am using Laravel-5.8 and Guzzle to consume an external api:
public function index()
{
try{
$myparam = 'JKK123';
$client = new Client();
$res = $client->request('GET','https://examplet/tracking/$myparam', [
'query' => ['key' => 'jkkffd091']
])->getBody();
$geoLocation = json_decode($res->getContents(), true);
$currentLocation = collect($geoLocation)->sortByDesc(function ($data) {
return Carbon::parse($data['Timestamp'])->format('d-m-Y h:i:s');
})->first();
$currentLocationFilter = explode(',', $currentLocation['current_asset_position_coord'] ?? '');
dd($currentLocationFilter);
return view('index', [
'currentLocation' => $currentLocation,
'currentLocationFilter' => $currentLocationFilter,
'geoLocation' => $geoLocation
]);
}catch (Exception $exception) {
Log::error($exception);
return back();
}
}
I am trying to pass the variable as parameter to the API. I didn't put it directly because it changes. I just tried to test.
When I did this as shown in the code above
$res = $client->request('GET','https://examplet/tracking/$myparam', [ ...
and then
dd($currentLocationFilter);
I got:
array:1 [▼
0 => ""
]
But when I put the value directly,
$res = $client->request('GET','https://examplet/tracking/JKK123', [
I got the required result:
array:2 [▼
0 => "2.1234565432145"
1 => "1.7864321249555"
]
How do I paa the variable as parameter into the external API?
Thanks
Use double quotes for executing variable like this:
$res = $client->request('GET',"https://examplet/tracking/{$myparam}", [...
I have a POST request with Guzzle like this:
// Return a collection
$cart = $this->getCart('2019-10-08 07:08:39');
//Return first entry of the collection with first()
$template = $this->getTemplate($config->key);
$isDetail = null;
foreach ($cart as $item) {
try {
$client = $this->getClient();
$headers = ['Content-Type' => 'application/json'];
$body = [
'user_id' => $item->mystore_user_id,
'title' => $template->title,
'message' => $template->message,
'avatar' => $template->avatar,
'detail_id' => $isDetail,
'schedule' => null
];
print_r($body);
$response = $client->post('push-noti/unicast', $headers, $body);
print_r(response()->json(json_decode($response->getBody(), true)));
} catch (QueryException | \Exception $ex) {
echo "Error!";
}
}
My body variable value is exist in each loop when it printed. But when I use it in $client->post, my request return error with user_id, title, message is required. I really don't know why is it?
Can you tell me what's wrong in my code?
Thank you!
Try
$response = $client->post('push-noti/unicast', ['body' => $body , 'headers' => $headers]);
If you are calling a third party API, replace push-noti/unicast with complete URL.
I have a URL used in blade template as:
href="{{ route('download', ['year' => $year, 'month' => $month, 'file' => $file_path]) }}"
when I am running my code then it is giving me an error as:
Undefined variable: year (View: C:\wamp64\www\Blog\employee-portal\resources\views\finance\invoice\edit.blade.php)
How can i define this $year variable in my controller?
In my controller the function is written as:
public function download($year, $month, $file, $inline = true)
{
$headers = [
'content-type' => 'application/pdf',
];
$file_path = FileHelper::getFilePath($year, $month, $file);
if (!$file_path) {
return false;
}
if ($inline) {
return Response::make(Storage::get($file_path), 200, $headers);
}
return Storage::download($file_path);
}
}
Edit function is written as:
public function edit(Invoice $invoice)
{
$projectStageBillings = $invoice->projectStageBillings;
$projectStageBilling = $projectStageBillings->first();
$client = $projectStageBilling->projectStage->project->client;
$client->load('projects', 'projects.stages', 'projects.stages.billings');
$billings = [];
foreach ($projectStageBillings as $key => $billing) {
$billing->load('projectStage', 'projectStage.project');
$billings[] = $billing;
}
return view('finance.invoice.edit')->with([
'invoice' => $invoice,
'clients' => Client::select('id', 'name')->get(),
'invoice_client' => $client,
'invoice_billings' => $billings,
]);
}
This error states that the view finance\invoice\edit.blade.php is missing the variable $year. And it is true, take a look at the return of your edit function:
return view('finance.invoice.edit')->with([
'invoice' => $invoice,
'clients' => Client::select('id', 'name')->get(),
'invoice_client' => $client,
'invoice_billings' => $billings,
]);
You are not sending any $year variable to the view here (the variables sent to the view are invoice,clients,invoice_client and invoice_billings.
To solve your problem, just send a $year variable to the view and you'll be ok :)