1

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?

2
  • use laravel.com/docs/5.1/queries to select data from db and use toArray() method.. Commented Jul 29, 2015 at 11:03
  • That wont work as I'm creating a query that used two databases Commented Jul 29, 2015 at 11:12

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.