Diao Vũ
Diao Vũ

Reputation: 109

Invalid argument supplied for foreach() when export excel file using Maatwebsite

I am very new to Laravel and PHP, just trying to export a table html to excel file, using this Maatwebsite

Follow this hdtuto

This is my function

public function exportFile($id){
                $products = DB::table('duan')
                ->whereIn('MaDA', $id)
                ->get();
                return \Excel::create('Filename', function($excel) use ($products) {
                            $excel->sheet('sheet name', function($sheet) use ($products)
                            {
                                $sheet->fromArray($products);
                            });

                })->download('xlsx');
        }

But I have the warning: Invalid argument supplied for foreach(). Any suggestion? Thanks in advance

Upvotes: 1

Views: 1162

Answers (1)

Hasan Teoman Tıngır
Hasan Teoman Tıngır

Reputation: 2901

You are getting Invalid argument supplied for foreach() error because php couldn't find items (array or object) for iterate in foreach loop. There is a misspelling in your query and it causes to return you null

public function exportFile($id){
                $products = DB::table('duan')
                ->whereIn('MaDA', $id) // you need to put $id in array like [$id]
                ->get();

                return \Excel::create('Filename', function($excel) use ($products) {
                         $excel->sheet('sheet name', function($sheet) use ($products)
                            {
                                $sheet->fromArray($products);
                            });

                })->download('xlsx');
 }

Upvotes: 1

Related Questions