Laravel Excel Cannot use object of type stdClass as array - excel

I'm having to use DB::select instead of calling a Model because my data structure is too complex.
My main SQL query is;
/* main mysql query */
$sql = "SELECT t1.* FROM `contracts`.`payments` as t1 LEFT JOIN `postcodes`.`" . $postcode_dataset . "` AS t2 ON t1.`VendorZIP` = t2.`postcode` WHERE ";
foreach ($unserialized_input as $key => $value) {
$sql .= "t2." . $key . " IN ('".implode("', '", $unserialized_input[$key])."') OR ";
}
$sql = rtrim($sql, " OR ");
$payments = DB::select($sql);
I am trying to use Maatwebsite Excel to export the result by doing this;
Excel::create('SME_Payments_Export-U', function($excel) use ($payments) {
$excel->sheet('Excel sheet', function($sheet) use ($payments) {
$sheet->setOrientation('landscape');
$sheet->fromArray($payments);
});
})->export('csv');
But I get the error;
Cannot use object of type stdClass as array
Here is a sample of my var_dump;
array(176) {
[0]=>
object(stdClass)#302 (4) {
["Fiscal Year"]=>
string(5) "13/14"
["Contract Number"]=>
string(0) ""
["Foreign Ind"]=>
string(1) "N"
["Valued or Running"]=>
string(1) "R"
}
[1]=>
object(stdClass)#304 (4) {
["Fiscal Year"]=>
string(5) "13/14"
["Contract Number"]=>
string(0) ""
["Foreign Ind"]=>
string(1) "Y"
["Valued or Running"]=>
string(1) "V"
}
[2]=>
object(stdClass)#305 (4) {
["Fiscal Year"]=>
string(5) "13/14"
["Contract Number"]=>
string(0) ""
["Foreign Ind"]=>
string(1) "N"
["Valued or Running"]=>
string(1) "R"
}
How can I convert payments?

As per documentation you need to transform array of objects to array of arrays before passing it to fromArray() method:
foreach ($payments as &$payment) {
$payment = (array)$payment;
}
$sheet->fromArray($payments);

I have faced same problem and what worked for me best is:
$payments = json_decode( json_encode($payments), true);
This will convert object/array to array and make it usable.

Related

Fixed array name to Dynamic

I would like to change a fixed array name to a dynamic array name.
Within a
set item_classes = [
item.original_link.nid and item.original_link.p6 and item.original_link.in_active_trail ? 'active',
]
This works because the 'nid' and p6 are the same and unique.
Within the item.original_link array there are 19 values:
'nid' => string(3) "114" - Node ID
'bid' => string(3) "100"
'pid' => string(3) "111"
'has_children' => string(1) "0"
'weight' => string(1) "0"
'depth' => string(1) "3" - Page Depth
'p1' => string(3) "100"
'p2' => string(3) "111"
'p3' => string(3) "114" - P+Depth
'p4' => string(1) "0"
'p5' => string(1) "0"
'p6' => string(1) "0"
'p7' => string(1) "0"
'p8' => string(1) "0"
'p9' => string(1) "0"
'in_active_trail' => boolTRUE
'access' => boolTRUE
'title' => string(21) "Development.twig.html"
'options' => array(0)
I need to set the value of the item.original_link.p6 to a dynamic value of: 'p + depth'.
As in this example, the value would be item.original_link.p3.
I hope I have explained this in enough detail for someone to help or give me direction.
I have added a set variable as below:
{% set my_var = [ ('p' ~ item.original_link.depth ), ] %}
This gives me the desired dynamic variable, but when I use this in the next set as below:
{% set item_classes = [ item.original_link.nid and item.original_link.my_var and item.original_link.in_active_trail ? 'is_active', ] %}
it returns NULL

2019 Failed to call to new PHPMailer that does not create an instance of PHPMailer Version 6.0.7

Failed to call new PHPMailer and does not create an instance of PHPMailer. The setting of $mail->SMTPDebug creates a stdClass instance, and then calling a non-existent method on it (isSMTP) fails. So it's all down to that instance creation failure. PHPMailer Version 6.0.7 Live Hosting Service
I have tried $mail = new stdClass();
or $mail = NULL; This is symptom fix but does not the cause and causes my page to send an email every time it loads.
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/Exception.php';
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
if(isset($_POST[‘submit’]))
$mail = new PHPMailer(true);
$mail->SMTPDebug = 2; // 0 = off (for production use) - 1 = client messages - 2 = client and server messages
$mail->isSMTP();
$mail->Host = 'mail.email.org';
$mail->SMTPSecure = 'ssl'; <-- Recommend by the hosting service
$mail->Port = 465; <-- Recommend by the hosting service <--Hosting Service Docs verify this
$mail->SMTPAuth = true;
$mail->Username = 'Mail#email.org';
$mail->Password = 'Using the correct Password';
$to = 'Mail#email.org'; <-- sending this to myself
$from = 'Mail#email.org'; <--sending to myself
$first_name = ((isset($_POST['FirstName']))&&(!is_null($_POST['FirstName'])))? $_POST['FirstName']:'';
$last_name = ((isset($_POST['LastName']))&&(!is_null($_POST['LastName'])))? $_POST['LastName']:'';
$email = ((isset($_POST['Email']))&&(!is_null($_POST['Email'])))? $_POST['Email']:'';
$age = ((isset($_POST['Age']))&&(!is_null($_POST['Age'])))? $_POST['Age']:'';
$student = ((isset($_POST['Student']))&&(!is_null($_POST['Student'])))? $_POST['Student']:'';
$agree18 = ((isset($_POST['Agree18']))&&(!is_null($_POST['Agree18'])))? $_POST['Agree18']:'';
/* Set the mail sender. */
$mail->setFrom( $to , 'Research');
/* Add a recipient. */
$mail->addAddress( $_POST['Email'] , 'Research');
/* Set the subject. */
$mail->Subject = 'Learn More about Research Requested';
$mail->isHTML(TRUE);
$mail->Body = '<html> "First Name:" . $first_name . " Last Name:" . $last_name . " Email:". $email . " Age:" . $age . " Student:" . $student . " Agree18:" . $agree18 . ""
</html>';
$mail->AltBody = ' "First Name:" . $first_name . " Last Name:" . $last_name . " Email:". $email . " Age:" . $age . " Student:" . $student . " Agree18:" . $agree18 . ""
';
if($mail->send()){
$msg="Your email msg has been send";
}else{
$msg="mail msg has not been send";
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
?>
Hope to find a solution to why it's failing.
Removed all my code, Performed what synchro stated and got this:
object(PHPMailer\PHPMailer\PHPMailer)#1 (74) { ["Priority"]=> NULL ["CharSet"]=> string(10) "iso-8859-1" ["ContentType"]=> string(10) "text/plain" ["Encoding"]=> string(4) "8bit" ["ErrorInfo"]=> string(0) "" ["From"]=> string(14) "root#localhost" ["FromName"]=> string(9) "Root User" ["Sender"]=> string(0) "" ["Subject"]=> string(0) "" ["Body"]=> string(0) "" ["AltBody"]=> string(0) "" ["Ical"]=> string(0) ""
["MIMEBody":protected]=> string(0) "" ["MIMEHeader":protected]=> string(0) "" ["mailHeader":protected]=> string(0) "" ["WordWrap"]=> int(0) ["Mailer"]=> string(4) "mail" ["Sendmail"]=> string(18) "/usr/sbin/sendmail" ["UseSendmailOptions"]=> bool(true) ["ConfirmReadingTo"]=> string(0) "" ["Hostname"]=> string(0) "" ["MessageID"]=> string(0) "" ["MessageDate"]=> string(0) "" ["Host"]=> string(9) "localhost" ["Port"]=> int(25)
"Helo"]=> string(0) "" ["SMTPSecure"]=> string(0) "" ["SMTPAutoTLS"]=> bool(true) ["SMTPAuth"]=> bool(false) ["SMTPOptions"]=> array(0) { } ["Username"]=> string(0) "" ["Password"]=> string(0) "" ["AuthType"]=> string(0) "" ["oauth":protected]=> NULL ["Timeout"]=> int(300) ["dsn"]=> string(0) "" ["SMTPDebug"]=> int(0) ["Debugoutput"]=> string(4) "html" ["SMTPKeepAlive"]=> bool(false) ["SingleTo"]=> bool(false)
["SingleToArray":protected]=> array(0) { } ["do_verp"]=> bool(false) ["AllowEmpty"]=> bool(false) ["DKIM_selector"]=> string(0) "" ["DKIM_identity"]=> string(0) "" ["DKIM_passphrase"]=> string(0) "" ["DKIM_domain"]=> string(0) "" ["DKIM_copyHeaderFields"]=> bool(true) ["DKIM_extraHeaders"]=> array(0) { } ["DKIM_private"]=> string(0) "" ["DKIM_private_string"]=> string(0) "" ["action_function"]=> string(0) ""
"XMailer"]=> string(0) "" ["smtp":protected]=> NULL ["to":protected]=> array(0) { } ["cc":protected]=> array(0) { } ["bcc":protected]=> array(0) { } ["ReplyTo":protected]=> array(0) { } ["all_recipients":protected]=> array(0) { } ["RecipientsQueue":protected]=> array(0) { } ["ReplyToQueue":protected]=> array(0) { } ["attachment":protected]=> array(0) { } ["CustomHeader":protected]=> array(0) { }
"lastMessageID":protected]=> string(0) "" ["message_type":protected]=> string(0) "" ["boundary":protected]=> array(0) { } ["language":protected]=> array(0) { } ["error_count":protected]=> int(0) ["sign_cert_file":protected]=> string(0) "" ["sign_key_file":protected]=> string(0) "" ["sign_extracerts_file":protected]=> string(0) "" ["sign_key_pass":protected]=> string(0) "" ["exceptions":protected]=> bool(false) ["uniqueid":protected]=> string(0) ""
This is a duplicate of your previous question with a different title.
When you have code that doesn't work, cut it back to a minimal example so that you exclude opportunities for ambiguity, and enable verbose, visible error reporting:
use PHPMailer\PHPMailer\PHPMailer;
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require 'PHPMailer/PHPMailer.php';
$mail = new PHPMailer;
var_dump($mail);
If that doesn't work, a more complex script isn't going to work either. For this to fail, I would suspect that there is something severely wrong with your PHP installation, and at the very least I would expect to see some warnings logged.
You forgot a bracket after condition with isset($_POST[...]).
if(isset($_POST['submit'])) {
// ^^
$mail = new PHPMailer(true);
$mail->SMTPDebug = 2; // 0 = off (for production use) - 1 = client messages - 2 = client and server messages
$mail->isSMTP();
...
}
// of course, don'f forget to add a closing one too here.
Fixed <-- Thanks to Synchro --> & Thanks Panthers for the input
Added use PHPMailer\PHPMailer\SMTP; <- This fixed most of my issues but not always required per Synchro
For working example with PHPMailer 6.0.7 look for Synchro's
This is a duplicate of your previous question with a different title Link.

Multiple If in single filter

if [CREATION_DATE] == ""
{
mutate {
convert => [ "CREATION_DATE", "string" ]
}
}
else
{
date {
locale => "en"
match => [ "CREATION_DATE", "dd-MMM-yy hh.mm.ss.SSS a"]
target => "CREATION_DATE"
}
}
if [SUBMITTED_DATE] == ""
{
mutate {
convert => [ "SUBMITTED_DATE", "string" ]
}
}
else
{
date {
locale => "en"
match => [ "SUBMITTED_DATE", "dd-MMM-yy hh.mm.ss.SSS a"]
target => "SUBMITTED_DATE"
}
}
if [LAST_MODIFIED_DATE] == ""
{
mutate {
convert => [ "LAST_MODIFIED_DATE", "string" ]
}
}
else
{
date {
locale => "en"
match => [ "LAST_MODIFIED_DATE", "dd-MMM-yy hh.mm.ss.SSS a"]
target => "LAST_MODIFIED_DATE"
}
}'
am getting output if i have all three (CREATION_DATE,SUBMITTED_DATE,LAST_MODIFIED_DATE) in date format.If any is STRING am not getting that log file in my input.
for ex:
my input is
12-JUL-13 11.33.56.259 AM,12-JUL-13 03.59.36.136 PM,12-JUL-13 04.00.05.584 PM
14-JUL-13 11.33.56.259 AM,11-JUL-13 04.00.05.584 PM
my output will come successfully for
12-JUL-13 11.33.56.259 AM,12-JUL-13 03.59.36.136 PM,12-JUL-13 04.00.05.584 PM
but NOT FOR 2nd line
In Simple,Logstash is indexing only when three if clauses have dates.
Help me out.THanks in advance!!
The issue with your if statements is pointed out by the comments by #Fairy and #alain-collins.
if [CREATION_DATE] == ""
Does not check if that field exists, it checks if it is an empty string.
Instead you could use a regex check to see if there is any content in the field using:
if [CREATION_DATE] =~ /.*/
and perform your date filter when this returns true.
Issue is solved when i change input format.
(New Format) 11-JUL-13 06.36.33.425000000 PM,13-JUL-13 06.36.33.425000000 PM,,
instead of
(Old format)11-JUL-13 06.36.33.425000000 PM,13-JUL-13 06.36.33.425000000 PM,"",
But My ques is still open.
I posted this because this solution might be useful to some.
Thanks!!!

Using boolean fields in groovy script in elasticsearch - doc['field_name'].value not working

The problem
I am trying to use boolean fields in a script to score. It seems like doc['boolean_field'].value can't be manipulated as a boolean, but _source.boolean_field.value can (even though the Scripting documentation here says "The native value of the field. For example, if its a short type, it will be short.").
What I've tried
I have a field called 'is_new'. This is the mapping:
PUT /test_index/test/_mapping
{
"test": {
"properties": {
"is_new": {
"type": "boolean"
}
}
}
}
I have some documents:
PUT test_index/test/1
{
"is_new": true
}
PUT test_index/test/2
{
"is_new": false
}
I want to do a function_score query that will have a score of 1 if new, and 0 if not:
GET test_index/test/_search
{
"query": {
"function_score": {
"query": {
"match_all": {}
},
"functions": [
{
"script_score": {
"script": "<<my script>>",
"lang": "groovy"
}
}
],
"boost_mode": "replace"
}
}
}
Scripts work when I use the _source.is_new.value field, but don't if I use doc['is_new'].value.
This works:
"if ( _source.is_new) {1} else {0}"
These don't work:
"if ( doc['is_new'].value) {1} else {0}" (always true)
"if ( doc['is_new'].value instanceof Boolean) {1} else {0}" (value isn't a Boolean)
"if ( doc['is_new'].value.toBoolean()) {1} else {0}" (always false)
"if ( doc['is_new']) {1} else {0}" (always true)
I've checked the value, and it thinks it is a string, but I can't do string comparison:
"if ( doc['is_new'].value instanceof String) {1} else {0}" (always true)
"if ( doc['is_new'].value == 'true') {1} else {0}" (always false)
"if ( doc['is_new'].value.equals('true')) {1} else {0}" (always false)
Is this broken, or am I doing it wrong? Apparently it is faster to use doc['field_name'].value, so if possible, it would be nice if this worked.
I am using Elasticsearch v1.4.4.
Thanks!
Isabel
I'm having the same issue on ElasticSearch v1.5.1: Boolean values in the document show up as characters in my script, T' for true and 'F' for false:
if ( doc['is_new'].value == 'T') {1} else {0}
I've just got it!
First, it works only with _source.myField, not with doc['myField'].value.
I think there's a bug there because the toBoolean() method should return a boolean depending on the actual value, but it doesn't.
But I also needed to declare the mapping of the field explicitly as boolean and not_analyzed.
I hope it helps!

remove objects from array elastic search

I have required to remove object from array that satisfies the condition, I am able to update the object of array on the basis of condition, which is as follow:
PUT twitter/twit/1
{"list":
[
{
"tweet_id": "1",
"a": "b"
},
{
"tweet_id": "123",
"a": "f"
}
]
}
POST /twitter/twit/1/_update
{"script":"foreach (item :ctx._source.list) {
if item['tweet_id'] == tweet_id) {
item['new_field'] = 'ghi';
}
}",
"params": {tweet_id": 123"}
}
this is working
for remove i am doing this
POST /twitter/twit/1/_update
{ "script": "foreach (item : ctx._source.list) {
if item['tweet_id'] == tweet_id) {
ctx._source.list.remove(item);
}
}",
"params": { tweet_id": "123" }
}
but this is not working and giving this error,
ElasticsearchIllegalArgumentException[failed to execute script];
nested: ConcurrentModificationException; Error:
ElasticsearchIllegalArgumentException[failed to execute script];
nested: ConcurrentModificationException
I am able to remove whole array or whole field using
"script": "ctx._source.remove('list')"
I am also able to remove object from array by specifying all the keys of an object using
"script":"ctx._source.list.remove(tag)",
"params" : {
"tag" : {"tweet_id": "123","a": "f"}
my node module elastic search version is 2.4.2 elastic search server is 1.3.2
You get that because you are trying to modify a list while iterating through it, meaning you want to change a list of object and, at the same time, listing those objects.
You instead need to do this:
POST /twitter/twit/1/_update
{
"script": "item_to_remove = nil; foreach (item : ctx._source.list) { if (item['tweet_id'] == tweet_id) { item_to_remove=item; } } if (item_to_remove != nil) ctx._source.list.remove(item_to_remove);",
"params": {"tweet_id": "123"}
}
If you have more than one item that matches the criteria, use a list instead:
POST /twitter/twit/1/_update
{
"script": "items_to_remove = []; foreach (item : ctx._source.list) { if (item['tweet_id'] == tweet_id) { items_to_remove.add(item); } } foreach (item : items_to_remove) {ctx._source.list.remove(item);}",
"params": {"tweet_id": "123"}
}
For people that need this working in elasticsearch 2.0 and up, the nil and foreach don't get recognized by groovy.
So here's a updated version, including a option to replace a item with the same id by a new object.
and also passing it the upsert will make sure the item gets added even if the document doesn't exist yet
{
"script": "item_to_remove = null; ctx._source.delivery.each { elem -> if (elem.id == item_to_add.id) { item_to_remove=elem; } }; if (item_to_remove != null) ctx._source.delivery.remove(item_to_remove); if (item_to_add.size() > 1) ctx._source.delivery += item_to_add;",
"params": {"item_to_add": {"id": "5", "title": "New item"}},
"upsert": [{"id": "5", "title": "New item"}]
}

Resources