3

I want to export the table but not all fields have to be exported. sorry my english is not very good...

function excel

public function excel()
    {
        $rekanan_internal = rekanan_internal::all();
        $selects = DB::table('rekanan_internal')->select('nama','description','pic','contact')->get();
        $selectsArray = [];
        $selectsArray = ['nama','description','pic','contact'];
        foreach ($selects as $select) 
        {
            $selectsArray = $select->toArray();
        } 

        Excel::create('rekanan_internal', function($excel) use($rekanan_internal){
            $excel->sheet('sheet1',function($sheet) use($selectsArray){
                $sheet->fromArray($rekanan_internal);
            });
        })->download('xlsx');
    }

getting error

FatalErrorException in ExportController.php line 31: Call to undefined method stdClass::toArray()

tereško
  • 56,151
  • 24
  • 92
  • 147
user8665248
  • 39
  • 1
  • 1
  • 4

1 Answers1

4

DB::table('xxxx')->get() will return a collection of stdClass. stdClass has no function toArray().

You probably want to make an array of the entire collection, in this case, you can replace the for loop with the following:

$selectsArray = $selects->toArray();

This is because a collection does have a function called toArray.

Update:
You could even shorten your code to the following:

$selectsArray = DB::table('rekanan_internal')
    ->select('nama','description','pic','contact')
    ->get()
    ->toArray();

Update 2:
For Laravel versions smaller than 5.3, you don't even need to cast the result to an array because the result is an array.

$selectsArray = DB::table('rekanan_internal')
    ->select('nama','description','pic','contact')
    ->get()
Jerodev
  • 29,019
  • 11
  • 72
  • 94