Insert data from excel (xlsm,xls) in laravel (cyber-duck) - php

Currently I can get the json data from my excel file with format like this
sample.xlsx
$excel = Importer::make('Excel');
$excel->hasHeader(true);
$excel->load($savePath.$fileName);
$collection = $excel->getCollection();
if(sizeof($collection[1]) == 5)
{
return $collection;
}
else
{
return redirect()
->back()
->with(['errors'=> [0=> 'Please provide date in file according to your format.']])
->with('modal',$modal);
}
output
[{"id":1,"first_name":"j.doe17","last_name":"Jun Doe","email":"j.doe#gmail.com","birthdate":{"date":"1996-09-07 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Taipei"}},{"id":2,"first_name":"j.doe18","last_name":"Jun Doe","email":"jan.doe#gmail.com","birthdate":{"date":"1996-09-07 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Taipei"}}]
Now I'm trying to use this code, just insert those json data to my database table > tbl_sampleimport
foreach ($collection->toArray() as $key => $value) {
foreach ($value as $row) {
$insert_data[] = array(
'first_name' => $row['first_name'],
'last_name' => $row['last_name'],
'email' => $row['email'],
'birthdate' => $row['birthdate'],
'created_at' => now(),
'updated_at' => now(),
);
}
}
DB::table('tbl_sampleimport')->insert($insert_data);
My Table tbl_sampleimport
But this gives me an error like this Illegal string offset 'first_name'
Laravel : v5.8.*
cyber-duck/laravel-excel

use json_decode() to convert into array
$arr = json_decode($collection, true);
foreach($arr as $row) {
$insert_data[] = array(
'first_name' => $row['first_name'],
'last_name' => $row['last_name'],
'email' => $row['email'],
'birthdate' => $row['birthdate']['date'],
'created_at' => now(),
'updated_at' => now(),
);
}

Related

create array dynamic Laravel PHP

i want when Foreach my Data , For Loop Add Data to Resume Array , exmaple :
Source :
foreach($getusers as $val) // 2record get data from bank But Just 1 record add to Array :(
{
$arr_data =array([
'username'=> $sec->dekey($val->user_username),
'info' => $sec->dekey($val->user_info),
'mobile' => $sec->dekey($val->user_phone),
'code' => $sec->dekey($val->user_code),
'jobside' => $val->user_jobside,
'status' => $val->user_status,
'datetime' => $val->datetime,
'userid' => $val->id,
]);
}
Export :
[{"username":"091584440004","info":"\u062d\u0627\u0646\u06cc\u0647 \u0631\u0648\u062d\u06cc","mobile":"09154479303","code":"091584440004","jobside":"EXPERT","status":"ACTIVE","datetime":"1399/08/13 - 19:26:37","userid":6}]
i want to :
[{"username":"091584440004", info ......]},[{"username":"0921538242",info ......]}, ....
Thanks .
You are overwriting your array instead of adding to it.
To initialise an array, you do:
$arr_data = []
And to append to it:
$arr_data[] = ['new' => 'entry'];
In your example:
$arr_data = [];
foreach($getusers as $val) {
$arr_data[] = [
'username'=> $sec->dekey($val->user_username),
'info' => $sec->dekey($val->user_info),
'mobile' => $sec->dekey($val->user_phone),
'code' => $sec->dekey($val->user_code),
'jobside' => $val->user_jobside,
'status' => $val->user_status,
'datetime' => $val->datetime,
'userid' => $val->id,
];
}

Uploading JSON file to MYSQL using Laravel not working

I am working on a script to upload a JSON file with all our COmpany data from our previous CRM system into a MYSQL database using laravel and i am running into an issue will parsing the json data. I have converted it to an array and run a foreach to upload each company, but it is throwing an error saying it cant convert from array to string. Im unsure what i am doing wrong here, my code is below as well as one company (all are very similar):
public function uploadCompanies()
{
$json = File::get("database/data/accounts.json");
$data = json_decode($json);
foreach($data as $item) {
DB::table('ucustomers')->insert(
[
'dynamics_guid' => $item->accountid,
'customer_code' => $item->mc_unleashedcode,
'customer_name' => $item->name,
'phone_number' => $item->telephone1,
'fax_number' => $item->fax,
'email' => $item->emailaddress1,
'website' => $item->websiteurl,
'override_reps' => [],
'updated_at' => date('Y-m-d H:i')
]
);
}
}
accounts.json
[
{
"#odata.etag": "W/\"145746454\"",
"name": "Core Pharmacy",
"opendeals": 0,
"modifiedon": "2020-08-29T14:11:19Z",
"address1_stateorprovince": "VIC",
"telephone1": "03 9338 1504",
"accountid": "5b46f158-d8ef-e911-a812-000d3a799888",
"websiteurl": null,
"mc_unleashedcode": "C1000096",
"fax": "03 9334 5030"
"emailaddress1": "tullamarine#locale.com.au",
}
]
ERROR
ErrorException
Array to string conversion
at vendor/laravel/framework/src/Illuminate/Support/Str.php:488
484|
485| $result = array_shift($segments);
486|
487| foreach ($segments as $segment) {
> 488| $result .= (array_shift($replace) ?? $search).$segment;
489| }
490|
491| return $result;
492| }
+8 vendor frames
9 app/Unleashed/DynamicsUpload.php:52
Illuminate\Database\Query\Builder::insert()
10 app/Console/Commands/InsertDynamicsData.php:41
App\Unleashed\DynamicsUpload::uploadCompanies()
Your problem is. you try to assign array to string when insert:
public function uploadCompanies()
{
$json = File::get("database/data/accounts.json");
$data = json_decode($json);
foreach($data as $item) {
DB::table('ucustomers')->insert(
[
'dynamics_guid' => $item->accountid,
'customer_code' => $item->mc_unleashedcode,
'customer_name' => $item->name,
'phone_number' => $item->telephone1,
'fax_number' => $item->fax,
'email' => $item->emailaddress1,
'website' => $item->websiteurl,
'override_reps' => [], // error on this one
'updated_at' => date('Y-m-d H:i')
]
);
}
}
there are 2 solution to fixed it.
if you want to insert array to table direct you need to encode it like below:
public function uploadCompanies()
{
$json = File::get("database/data/accounts.json");
$data = json_decode($json);
foreach($data as $item) {
DB::table('ucustomers')->insert(
[
'dynamics_guid' => $item->accountid,
'customer_code' => $item->mc_unleashedcode,
'customer_name' => $item->name,
'phone_number' => $item->telephone1,
'fax_number' => $item->fax,
'email' => $item->emailaddress1,
'website' => $item->websiteurl,
'override_reps' => json_encode([]), // need to encode first
'updated_at' => date('Y-m-d H:i')
]
);
}
}
solution 2 is using model for create:
but first you need to cast override_reps field to array. so laravel will handle it for you
// assume you model name Customer
class Customer extends Model
{
protected $casts =[
'override_reps'=>'array',
];
}
// on controller
public function uploadCompanies()
{
$json = File::get("database/data/accounts.json");
$data = json_decode($json);
foreach($data as $item) {
Customer::create(
[
'dynamics_guid' => $item->accountid,
'customer_code' => $item->mc_unleashedcode,
'customer_name' => $item->name,
'phone_number' => $item->telephone1,
'fax_number' => $item->fax,
'email' => $item->emailaddress1,
'website' => $item->websiteurl,
'override_reps' => [],//lavavel model will encode it before insert
'updated_at' => date('Y-m-d H:i')
]
);
}
}

Removing an Array Object if key is found

How can I remove a whole array object if a $key=>value matches?
For example in my data I have ["endDate"]=> string(10) "2017-06-24" and if that date matches todays date('Y-m-d') I would like the whole object bock to be removed from the $row
Code:
foreach ($json->data as $row)
{
$date = date('Y-m-d');
if($row->endDate == $date){
$search = array_search($date, array_column('endDate', $row));
unset($row[$search]);
if (!in_array($row->guestEmail, $emails) && date('Y-m-d', strtotime($row->startDate))== date('Y-m-d'))
{
$guests[] = array(
'FirstName' => $row->guestFirstName,
'LastName' => $row->guestLastName,
'email' => $row->guestEmail,
'country' => $row->guestCountry,
'check-in_date' => $row->startDate,
'check-out_date' => $row->endDate,
);
$emails[] = $row->guestEmail;
}
}
}
JSON:
$response = $o->curl(sprintf($url, $propertyID, $pageSize, $pageNumber, $resultsFrom));
$json = json_decode($response);
$date = date('Y-m-d');
foreach ($json->data as $index=> $row){
if($row->endDate == $date) unset($json->data{$index});
}
foreach ($json->data as $row){
if (!in_array($row->guestEmail, $emails) && date('Y-m-d', strtotime($row->startDate))== date('Y-m-d'))
{
$guests[] = array(
'FirstName' => $row->guestFirstName,
'LastName' => $row->guestLastName,
'email' => $row->guestEmail,
'country' => $row->guestCountry,
'check-in_date' => $row->startDate,
'check-out_date' => $row->endDate,
);
$emails[] = $row->guestEmail;
}
}
You may also consider just skipping to the next iteration, since it looks like you are building a guest email list and are not trying to modify the source of the json feed.
$date = date('Y-m-d');
foreach ($json->data as $row){
if($row->endDate == $date) {
continue;
}
if (!in_array($row->guestEmail, $emails) && date('Y-m-d', strtotime($row->startDate))== date('Y-m-d'))
{
$guests[] = array(
'FirstName' => $row->guestFirstName,
'LastName' => $row->guestLastName,
'email' => $row->guestEmail,
'country' => $row->guestCountry,
'check-in_date' => $row->startDate,
'check-out_date' => $row->endDate,
);
$emails[] = $row->guestEmail;
}
}
Between the two options I pose, the second one requires less code and will yield slightly faster execution times.
If you place an ampersand before $row in your foreach you can change $json->data directly. From what you wrote, I think I understand your question and this may be what you need.
foreach ($json->data as &$row)
{
$date = date('Y-m-d');
if ($row->endDate == $date) {
$search = array_search($date, array_column('endDate', get_object_vars($row)));
unset($row[$search]);
if (!in_array($row->guestEmail, $emails) && date('Y-m-d', strtotime($row->startDate))== date('Y-m-d'))
{
$guests[] = array(
'FirstName' => $row->guestFirstName,
'LastName' => $row->guestLastName,
'email' => $row->guestEmail,
'country' => $row->guestCountry,
'check-in_date' => $row->startDate,
'check-out_date' => $row->endDate,
);
$emails[] = $row->guestEmail;
}
}
}
If not then rephrase your question so I might provide the answer you need.

PHP MVC query to get all existing rows is returning only 1 row

I have a working query but its only returning 1 row - where or what can I do to return all existing rows?
Model:
public function getInfo() {
$info_query = $this->db->query("SELECT * FROM `km_info` WHERE ((date_start = '0000-00-00' OR date_start < NOW()) AND (date_end = '0000-00-00' OR date_end > NOW())) AND status = '1'");
if ($info_query->num_rows){
return array(
'info_id' => $info_query->row['info_id'],
'name' => $info_query->row['name'],
'amount' => $info_query->row['amount'],
'date_start' => $info_query->row['date_start'],
'date_end' => $info_query->row['date_end'],
'status' => $info_query->row['status'],
'date_added' => $info_query->row['date_added']
);
}
}
Controller:
$info_options = $this->model_extension_total_info->getInfo();
if ($info_options){
$json['info_options'] = array();
$json['info_options'][] = array(
'info_id' => $info_options['info_id'],
'name' => $info_options['name'],
'amount' => $info_options['amount'],
'date_start' => $info_options['date_start'],
'date_end' => $info_options['date_end'],
'status' => $info_options['status'],
'date_added' => $info_options['date_added']
);
}
When I try foreach() in the controller, I still only get one row.:
foreach ($info_options as $info) {
var_dump($info_options['name']);exit;
//var_dump($info_options['name']); results: Warning: Illegal string offset 'name'
}
In the model, when I dump:
$info_query I get 9 -- which is all of the rows I'm expecting.
Not particularly certain what I'm missing or doing wrong.
You're not looping over the result. Not in model nor in the controller. Though I don't know why you'd do this twice. Maybe I'm just not understanding your code.
Model:
$data = [];
if ($info_query->num_rows){
foreach ($info_query->result() as $row) {
$data[] = array(
'info_id' => $row['info_id'],
'name' => $row['name'],
'amount' => $row['amount'],
'date_start' => $row['date_start'],
'date_end' => $row['date_end'],
'status' => $row['status'],
'date_added' => $row['date_added']
);
}
return $data;
}
Controller:
$info_options = $this->model_extension_total_info->getInfo();
$json['info_options'] = array();
if ($info_options){
foreach ($info_options as $info) {
$json['info_options'][] = array(
'info_id' => $info['info_id'],
'name' => $info['name'],
'amount' => $info['amount'],
'date_start' => $info['date_start'],
'date_end' => $info['date_end'],
'status' => $info['status'],
'date_added' => $info['date_added']
);
}
}
Technically, you don't have to loop at all. You can just:
public function getInfo() {
$info_query = $this->db->query("SELECT * FROM `km_info` WHERE ((date_start = '0000-00-00' OR date_start < NOW()) AND (date_end = '0000-00-00' OR date_end > NOW())) AND status = '1'");
if ($info_query->num_rows){
return $info_query->result();
}
else
{
return false;
}
}
and
$info_options = $this->model_extension_total_info->getInfo();
// and that's it, just do whatever you need with $info_options

Laravel - prepared statement contains too many placeholders

Im wondering if someone could give me a hand.
I have written an import script, it works fine for a small number of points, but when i start importing large numbers, i get the following error:
General error: 1390 Prepared statement contains too many placeholders
The code that im using to import is as follows:
foreach ( $items as $item ) {
$insert[] = array(
'userid' => User::current()->id,
'lati' => $item[0],
'long' => $item[1],
'streetNumber' => $item[2],
'streetName' => $item[3],
'country' => $item[6],
'state' => $item[5],
'pcode' => $item[7],
'suburb' => $suburb,
'created_at' => new DateTime,
'updated_at' => new DateTime
);
}
if(DB::table('mytable')->insert($insert))
{
return true;
} else {
return false;
}
Any help with figuring out how to fix this would be greatly appreciated.
function addData($items) {
$itemsTemp = [];
if (count > 1000) {
$itemsTemp = array_slice($items, 1000);
$items = array_slice($items, 0, 1000);
}
foreach ( $items as $item ) {
$insert[] = [
'userid' => User::current()->id,
'lati' => $item[0],
'long' => $item[1],
'streetNumber' => $item[2],
'streetName' => $item[3],
'country' => $item[6],
'state' => $item[5],
'pcode' => $item[7],
'suburb' => $suburb,
'created_at' => new DateTime,
'updated_at' => new DateTime
];
}
if (DB::table('mytable')->insert($insert)) {
if ($itemsTemp) {
addData($itemsTemp);
}
} else {
return false;
}
return true;
}

Categories