Codeigniter - insert batch - multiple inputs with same name - mysql

I am trying to insert a batch of rows for wholesale, dealer and customer
Note : i am using 'append' to add row of inputs but then they carry the same input names.
I am trying to apply this to wholesale first but it is not happening
when i add another row to my wholesale input list it is taking only one row(my last row) input and my other row of inputs are discarded. the var_dump of array reveals that.
This is my controller file
$range = $this->input->post('wrange1');
$usertype = $this->input->post('wusertype');
$uom = $this->input->post('wuom1');
$price = $this->input->post('wamount1'); //array of price
$vat = $this->input->post('wvat1');
var_dump($range);// i am getting only one output
$updateArray = [];
for($x = 0; $x < sizeof($price); $x++){
$updateArray[$x] = array(
'product_id'=> $id,
'range' => $range[$x],
'usertype' => $usertype[$x],
'uom' => $uom[$x],
'price' => $price[$x],
'vat' => $vat[$x]
);
}
$this->productmodel->updatepricinglist($updateArray);
This is my model file:
public function updatepricinglist($updateArray) {
$this->db->insert_batch('product_pricing', $updateArray);
}

use insert operation inside for loop.and if you get the array in all the field then you have to use array of index like in for loop , since you said you get only one range at output then don't use array of index in loop.
$range = $this->input->post('wrange1');
$usertype = $this->input->post('wusertype');
$uom = $this->input->post('wuom1');
$price = $this->input->post('wamount1'); //array of price
$vat = $this->input->post('wvat1');
var_dump($range);// i am getting only one output
for($x = 0; $x < sizeof($price); $x++){
$updateArray = array(
'product_id'=> $id,
'range' => $range,
'usertype' => $usertype[$x],
'uom' => $uom[$x],
'price' => $price[$x],
'vat' => $vat[$x]
);
$this->productmodel->updatepricinglist($updateArray);
}

Related

How to retrive from other table and input it again into another table in laravel?

I want to retrieve some data from 'tbl_karyawan' and input into 'tbl_absen' which is if the NIP exist from 'tbl_karyawan' then parshing some data into 'tbl_absen'. I was create the code, and the data is going well. but i have something trouble with
i want the data input in Nip_kyn be like 'KIP001' not [{"Nip_kyn":"KIP001"}].
this is my Model
public function presensi($data)
{
$isExist = DB::table('tbl_karyawan')
->where('Nip_kyn', $data)->exists();
if ($isExist) {
$namakyn = DB::table('tbl_karyawan')->where($data)->get('Nama_kyn');
$nippppp = DB::table('tbl_karyawan')->where($data)->select('Nip_kyn')->get($data);
$values = array('Nip_kyn' => $nippppp, 'Nama_kyn' => $namakyn, 'Jam_msk' => now(), 'Log_date' => today());
DB::table('tbl_absen')->insert($values);
} else {
echo 'data not available';
}
}
this is my controller
public function get()
{
$day = [
'time_in' => $this->AbsenModel->timeIN(),
'time_out' => $this->AbsenModel->timeOut(),
'break' => $this->AbsenModel->break(),
// absen here
's' => $this->AbsenModel->absensi(),
];
$data = [
'Nip_kyn' => Request()->Nip_kyn,
];
$this->AbsenModel->presensi($data);
return view('v_absen', $data, $day);
}
Yup, I finally got it, the problem is on my model.
$nama_karyawan = DB::table('tbl_karyawan')->where($data)->value('Nama_kyn');
$nipkyn = DB::table('tbl_karyawan')->where($data)->value('Nip_kyn');
I just change 'get' to 'value'.

Need to insert array data using laravel controller

i have a array data like this below. i want to save some of it's data not all into mysql table.
when i dd($request->all) data in my controller function it looks like this.
array:1 [
"{"cart":" => array:1 [
"{"product":{"id":1,"category":1,"product_name":"Brinjal 500g","product_image":"1585409454.jpeg","product_price":232,"unit":"500g","product_description":null,"stock":"In Stock","product_status":1,"show":1,"delievery_date":null,"vendor":null,"quantity":18,"item_type":"feature_product","created_at":"2020-03-28T15:30:54.000000Z","updated_at":"2020-03-28T15:30:54.000000Z","deleted_at":null,"categories":{"id":1,"category_name":"Fresh Fruits","category_image":null,"category_description":null,"category_status":1,"show":0,"created_at":"2020-03-28T15:30:12.000000Z","updated_at":"2020-03-28T15:30:12.000000Z","deleted_at":null}},"quantity":1}" => null
]
]
i want to add id and total quantity shows last object into a table. table rows looks like this.
$table->increments('id');
$table->integer('order_id');
$table->integer('product_id')->unsigned();
$table->integer('total_quantity');
$table->timestamps();
$table->softDeletes();
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
how can i write a store function using this data in laravel
result data looks like this
Array
(
[{"cart":] => Array
(
[{"product":{"id":1,"category":1,"product_name":"Brinjal 500g","product_image":"1585409454.jpeg","product_price":232,"unit":"500g","product_description":null,"stock":"In Stock","product_status":1,"show":1,"delievery_date":null,"vendor":null,"quantity":18,"item_type":"feature_product","created_at":"2020-03-28T15:30:54.000000Z","updated_at":"2020-03-28T15:30:54.000000Z","deleted_at":null,"categories":{"id":1,"category_name":"Fresh Fruits","category_image":null,"category_description":null,"category_status":1,"show":0,"created_at":"2020-03-28T15:30:12.000000Z","updated_at":"2020-03-28T15:30:12.000000Z","deleted_at":null}},"quantity":1}] =>
)
)
this is my latest update
$data = [];
foreach ($request->all() as $key => $value) {
$data[$key]['product_id'] = $value['product']['id'];
$data[$key]['quantity'] = $value['quantity'];
dd($value);
}
Loop through your data coming and make array as below i have shown.
Try this one by creating the array of the data and insert array to the database as bulk data:
// this will decode your json data that you're getting in the post data
$postdata = json_decode($request->all(), true);
$data = [];
foreach ($postdata as $key => $value) {
$data[$key]['product_id'] = $value['product']['id'];
$data[$key]['quantity'] = $value['quantity'];
}
// $data now will have data as following structure
$data = [[
'product_id' => 2,
'total_quantity' => 7
],
[
'product_id' => 2,
'total_quantity' => 7
]];
$order = Order::create($data);

Api Response and Json laravel format

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

Add items to query result - Laravel

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]);

CakePHP 3.0 Modelless Pagination

I have data coming from an API that I want to show results for using CakePHP's pagination. Everything I see for the pagination requires a query or model object to be passed in. Is it possible to pass in something like an array of the data or total items, current item, and items per page?
The solution was easier than I anticipated. I was able to add a paging element to the request params. The pagination component doesn't need to be touched at all.
$data = $Utility->getData();
$perPage = 20;
$count = count($data);
$page = isset($this->request->query['page']) ? $this->request->query['page'] : 1;
$offset = $perPage * ($page - 1);
$pageCount = floor($count / $perPage);
$this->request->params['paging'] = [
'Messages' => [
'page' => $page,
'current' => $offset,
'count' => $count,
'perPage' => $perPage,
'prevPage' => $page != 1,
'nextPage' => $page != $pageCount,
'pageCount' => $pageCount,
]
];