I want to view MySQL data using array in CakePHP ctp file. What is the error in my code that I can't understand?
$this->loadModel('MacHistory');
$data = $this->MacHistory->find('all', array('conditions' => array('package_customer_id' => $pcid)));
$filteredData = array();
foreach ($data as $single) {
$mac[] = $single['MacHistory']['mac'];
$user_id[] = $single['MacHistory']['installed_by'];
$installation_date[] = $single['MacHistory']['installation_date'];
}
if (!empty($user_id)) {
$filteredData['mac'] = $mac;
$filteredData['user_id.'] = $user_id;
$filteredData['installation_date.'] = $installation_date;
$this->request->data['PackageCustomer'] = $filteredData;
}
$this->set(compact('filteredData'));
Related
How to update multiple inputs in Laravel? I have two tables: Order and Detail_Order. Here's my controller to create multiple inputs.
public function store($id_trip, Request $request){
$order = new Order();
$order->id_trip = $id_trip;
$order->id_users = Auth::guard('operator')->user()->id_users;
$order->date_order = date('Y-m-d H:i:s');
$order->id_users_operator = Auth::guard('operator')->user()->id_users;
$order->save();
foreach($request->passenger_name as $key => $value){
Detail_Order::create([
'id_trip' => $order->id_trip,
'id_seat' => $request->id_seat[$key],
'id_order' => $order->id_order,
'passenger_name' => $request->passenger_name[$key],
'address' => $request->address[$key],
'phone_number' => $request->phone_number[$key]
]);
}
}
I tried to update it, but I don't know how to update the Detail_order. Here's my update controller :
public function update($id_order, $id_trip, Request $request){
$order = Order::where(['id_order' => $id_order, 'id_trip' => $id_trip])->first();
$order->id_trip = $request->id_trip;
$order->id_users = Auth::guard('operator')->user()->id_users;
$order->save();
$detail = Detail_Order::where(['id_order' => $id_order, 'id_trip' => $id_trip])->get();
if(count($request->id_seat) > 0){
for($i = 0; $i < count($request->id_seat); $i++){
$detail[$i]->id_trip = $order->id_trip;
$detail[$i]->id_seat = $request->id_seat[$i];
$detail[$i]->id_order = $pesanan->id_order;
$detail[$i]->passenger_name = $request->passenger_name[$i];
$detail[$i]->address = $request->address[$i];
$detail[$i]->phone_number = $request->phone_number[$i];
$detail[$i]->save();
}
}
session()->flash('flash_success', 'Data has been updated');
return redirect('/order');
}
after $order->save(); line you can do something like this....
if it is work good .. if not you can comment below . i will give you solution...
$order->save();
$detail = Detail_Order::where('order_id', $order->id)->get();
if(count($request->id_seat) > 0){
for($i = 0; $i < count($request->id_seat); $i++){
$detail[$i]->order_id = $order->id;
$detail[$i]->id_seat = $request->id_seat[$i],
$detail[$i]->passenger_name = $request->passenger_name[$i];
$detail[$i]->save();
}
}
I want to remove commas when importing data from an excel file to the database and i use phpexcel library for importing the data
i have a controller like this for importing the excel file
M_excel.php
public function import(){
$user = $this->ion_auth->user()->row();
include APPPATH.'third_party/PHPExcel/PHPExcel.php';
$excelreader = new PHPExcel_Reader_Excel2007();
$loadexcel = $excelreader->load('excel/'.$this->filename.'.xlsx');
$sheet = $loadexcel->getActiveSheet()->toArray(null, true, true ,true);
$data = array();
$numrow = 4;
foreach($sheet as $row){
if($numrow > 4){
array_push($data, array(
'NO' => $row['A'],
'APIID' => $row['B'],
'Jan19' => $row['C'],
'Feb19' => $row['D'],
'Mar19' => $row['E'],
'Apr19' => $row['F'],
'May19' => $row['G'],
'Jun19' => $row['H'],
'Jul19' => $row['I'],
'Aug19' => $row['J'],
'Sep19' => $row['K'],
'Oct19' => $row['L'],
));
}
$numrow++;
}
$this->m_excel->insert_multiple($data);
redirect("excel_import");
}
Excel file
just replace the comma by using str_replace(",", "", "string here") like below
$data = array();
$i=0;
foreach($sheet as $row){
if($numrow > 4){
$data[$i]['NO'] = $row['A'];
$data[$i]['APIID'] = $row['B'];
$data[$i]['Jan19'] = str_replace(",", "", $row['C']) // use str_replace where you want to replace comma
$data[$i]['Feb19'] = $row['D'];
$data[$i]['Mar19'] = $row['E'];
$data[$i]['Apr19'] = $row['F'];
$data[$i]['May19'] = $row['G'];
$data[$i]['Jun19'] = $row['H'];
$data[$i]['Jul19'] = $row['I'];
$data[$i]['Aug19'] = $row['J'];
$data[$i]['Sep19'] = $row['K'];
$data[$i]['Oct19'] = $row['L'];
}
$i++;
$numrow++;
}
$this->m_excel->insert_multiple($data);
redirect("excel_import");
I'm using Laravel 5.7. and GuzzleHttp 6.0 to get API response
from endpoint
I'm passing query data from Blade form to this function.
public static function prhmulti($multisearch, $start ,$end)
{ $city = $multisearch['city'];
$client = new Client([
'base_uri' => 'https://avoindata.prh.fi/tr/',
'query' => [
'totalResults' => 'true',
'maxResults' => '1000',
'registeredOffice'=> $city,
'companyForm'=>'OY',
'companyRegistrationFrom'=>$start,
'companyRegistrationTo'=>$end,
],
'defaults'=>[
'timeout' => 2.0,
'cookies' => true,
'headers' => [
'content-type' => 'application/json',
'User-Agent' =>"GuzzleHttp/Laravel-App-5.7, Copyright MikroMike"
]]]);
$res = $client->request('GET','v1');
$ResData = json_decode($res->getBody()->getContents());
dd ($ResData) gives all data from API response.
But I am not able to return JSON back to other function
return $this->multisave($ResData);
public static function multisave (data $ResData)
This will parse JSON and
{
foreach ($data->results as $company) {
$name = $company->name;
$Addr = $company->addresses;
$businessId = $company->businessId;
$companyForm = $company->companyForm;
$registrationDate = $company->registrationDate;
foreach ($company->addresses as $Addr) {
$city = $Addr->city;
$postcode = $Addr->postCode;
$street = $Addr->street;
}
}
save data to Mysql.
$NewCompany = new Company();
$NewCompany = Company::updateOrCreate($array,[
[ 'vat_id', $businessId],
[ 'name', $name],
[ 'form',$companyForm],
[ 'street', $Addr],
[ 'postcode', $postcode],
[ 'city', $city],
[ 'regdate', $registrationDate],
]);
}
IF Parse part and Save part is inside same function code works ok(save only one company),
but I need to separate them because later on it's easier to maintain.
Error which I am getting to return $ResData
" Using $this when not in object context"
Information is in JSON array.
Also foreach part save ONLY one company ?
foreach ($data->results as $company) {
$name = $company->name;
$Addr = $company->addresses;
$businessId = $company->businessId;
$companyForm = $company->companyForm;
$registrationDate = $company->registrationDate;
foreach ($company->addresses as $Addr) {
$city = $Addr->city;
$postcode = $Addr->postCode;
$street = $Addr->street;
}
So : 1) What is best way to create own function for parse JSON
and other for save data to DB?
2) As foreach loop save only one company data, What is
best way to fix it?
Thanks MikroMike.
Resolved my own question for saving companies to db
First get total number inside Array
use for-loop to make counting
use foreach-loop extract information per single company as object.
$data = json_decode($res->getBody()->getContents());
$total = $data->totalResults;
for ($i = 0; $i < $total; $i++){
$NewCompany = new Company();
foreach ($data->results as $company)
{
$name = $company->name;
$businessId = $company->businessId;
$companyForm = $company->companyForm;
$registrationDate = $company->registrationDate;
$array = [];
Arr::set($array, 'vat_id', $businessId);
Arr::set($array, 'name', $name );
Arr::set($array, 'form', $companyForm);
Arr::set($array, 'regdate', $registrationDate);
$NewCompany = Company::updateOrCreate($array,[
[ 'vat_id', $businessId],
[ 'name', $name],
[ 'form',$companyForm],
[ 'regdate', $registrationDate],
]);
}// END OF MAIN FOREACH
}// END OF For loop
}// END OF FUCNTION
} // END OF CLASS
I have this function in Laravel 5.1
public function calcolaKilometri()
{
$partenza = Input::get('partenza');
$destinazione = Input::get('destinazione');
$distanceMatrix = new DistanceMatrix(new Client(), new GuzzleMessageFactory());
$response = $distanceMatrix->process(new DistanceMatrixRequest(
[$partenza],
[$destinazione]
));
foreach ($response->getRows() as $row) {
foreach ($row->getElements() as $element) {
$distance = $element->getDistance();
$text = $distance->text;
$value = $distance->value;
$data = ['text' => $text, 'value' => $value];
return \Response::json($data);
}
}
}
need to return to Ajax JSON data but this function return plain HTML response, because we are in a forech loop. How i can do the trick?
I'm not sure I fully understand what you're saying but I assume you want to return all of the data found when looping through your result set in a single JSON response.
Try something like this:
// Your previous code...
// Initialise a $data array here, that we're going to fill with data
$data = [];
foreach ($response->getRows() as $row) {
foreach ($row->getElements() as $element) {
$distance = $element->getDistance();
$text = $distance->text;
$value = $distance->value;
// Append the new set of data to your array
$data[] = ['text' => $text, 'value' => $value];
}
}
// Return the data as JSON only when we've filled it with everything
return response()->json($data);
Try This...
$json = json_encode($data);
return \Response::json($json);
Solved using sessions. If someone have the same issue:
public function calcolaKilometri()
{
$partenza = Input::get('partenza');
$destinazione = Input::get('destinazione');
$distanceMatrix = new DistanceMatrix(new Client(), new GuzzleMessageFactory());
$response = $distanceMatrix->process(new DistanceMatrixRequest(
[$partenza],
[$destinazione]
));
foreach ($response->getRows() as $row) {
foreach ($row->getElements() as $element) {
$text = $element->getDistance()->getText();
$value = $element->getDistance()->getValue();
\Session::put('testo', $text);
\Session::put('valore', $value);
}
}
// Return the data as JSON only when we've filled it with everything
$testo = \Session::get('testo');
$valore = \Session::get('valore');
$result = ['text' => $testo, 'value' => $valore];
return \Response::json($result);
}
I'm slowly moving my API to Laravel and coming to grips with the Query Builder.
I'm trying to achieve this:
$data = array();
$query = "SELECT * FROM blog_posts WHERE post_type = 3 AND post_status = 1 ORDER BY id DESC";
$result = mysqli_query($cms_connection, $query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
$row['post_seo'] = seoUrl($row['post_title']);
$data['data'][] = $row;
}
$data['success'] = true;
$response = json_encode($data);
}
My problem isn't necessarily with getting the query, but as you can see I'm using the result of the query and then injecting it back into the final array.
So essentially, I'm fetching rows, transforming some of the attributes fetched, and then injecting the newly created attributes into the resulting array.
This is what I have so far:
$posts = DB::table('blog_posts')
-where(['post_type' => 1, 'post_status' => 1)
->orderBy('id', 'desc')
->take(5)->get();
You could do it this way
// get your data (yours part of code)
$posts = DB::table('blog_posts')
-where(['post_type' => 1, 'post_status' => 1])
->orderBy('id', 'desc')
->take(5)->get();
// add post_seo
foreach ($posts as $post) {
$post->post_seo = seoUrl($post->post_title);
}
// set result array
$data['data'] = $posts;
$data['success'] = true;
// response
$response = response()->json($data);
// or in case you want to return it just
return response()->json($data);
EDIT
You could do it also a bit better, using Eloquent. If you have such model (you need to add valid namespaces and use statements)
class BlogModel extends Model
{
protected $table = 'blog_posts';
protected $appends = ['post_seo'];
public function getPostSeoAttribute($value)
{
return seoUrl($this->post_title);
}
}
(added accessor to post_seo attribute and added post_seo to results when converting to array)
You can now do (shorter syntax than in previous example):
// get your data
$posts = BlogPost::where('post_type',1)
->where('post_status',1)
->orderBy('id', 'desc')
->take(5)->get();
// response
$response = response()->json(['data' => $posts, 'success' => true]);