Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object of class stdClass could not be converted to string - laravel

Tags:

php

excel

laravel

I am following this documentation

to implement export to Excel in my laravel 4 project.

So am trying to generate excel file from array like this:

//$results is taken with db query

$data = array();
foreach ($results as $result) {
   $result->filed1 = 'some modification';
   $result->filed2 = 'some modification2';
   $data[] = $result;
}
Excel::create('Filename', function($excel) use($data) {

$excel->sheet('Sheetname', function($sheet) use($data) {

    $sheet->fromArray($data);

      });

})->export('xls');

But this raises exception:

  Object of class stdClass could not be converted to string

What am I doing wrong ?

UPDATE:

Tried this:

$data = get_object_vars($data);

which results in:

get_object_vars() expects parameter 1 to be object, array given

This:

$data = (array)$data;

Results in the initial error.

like image 356
Alexander Nikolov Avatar asked May 15 '15 12:05

Alexander Nikolov


4 Answers

Try this simple in one line of code:-

$data= json_decode( json_encode($data), true);

Hope it helps :)

like image 185
kunal Avatar answered Nov 07 '22 09:11

kunal


$data is indeed an array, but it's made up of objects.

Convert its content to array before creating it:

$data = array();
foreach ($results as $result) {
   $result->filed1 = 'some modification';
   $result->filed2 = 'some modification2';
   $data[] = (array)$result;  
   #or first convert it and then change its properties using 
   #an array syntax, it's up to you
}
Excel::create(....
like image 37
Damien Pirsy Avatar answered Nov 07 '22 10:11

Damien Pirsy


You might need to change your object to an array first. I dont know what export does, but I assume its expecting an array.

You can either use

get_object_vars()

Or if its a simple object, you can just typecast it.

$arr = (array) $Object;

like image 9
Kishor Kurian Avatar answered Nov 07 '22 09:11

Kishor Kurian


If you have a Collection of stdClass objects, you could try with this:

$data = $data->map(function ($item){
            return get_object_vars($item);
        });
like image 2
Edujugon Avatar answered Nov 07 '22 11:11

Edujugon