Laravel导出Excel报错:Query\Builder::toArray()方法未定义
Fixing "Call to undefined method Illuminate\Database\Query\Builder::toArray()" Error in Excel Export
Hey there, let's fix that frustrating error you're hitting when trying to export your database data to Excel!
What's Causing the Error?
The root issue is straightforward: DB::table('importpdfs') returns an Illuminate\Database\Query\Builder object, not a ready-to-use collection or array. The toArray() method doesn't exist on the Query Builder—you need to first execute the query to fetch your actual data.
Corrected Controller Code
Here's the fixed version of your excel() function:
function excel() { // Execute the query with get() to get a collection, then convert to array $pdf_data = DB::table('importpdfs')->get()->toArray(); $pdf_array[] = array('Battery', 'No_of_questions_attempted', 'SAS', 'NPR', 'ST', 'GR'); foreach ($pdf_data as $pdf) { $pdf_array[] = array( 'Battery' => $pdf->Battery, 'No_of_questions_attempted' => $pdf->No_of_questions_attempted, 'SAS' => $pdf->SAS, 'NPR' => $pdf->NPR, 'ST' => $pdf->ST, 'GR' => $pdf->GR ); } // Return the download response so Laravel sends it to the browser return Excel::download('Pdf Data', function ($excel) use ($pdf_array) { $excel->setTitle('Pdf Data'); $excel->sheet('Pdf Data', function ($sheet) use ($pdf_array) { $sheet->fromArray($pdf_array, null, 'A1', false, false); }); }, 'pdf_data.xlsx'); }
Key Changes Explained
- Added
get()beforetoArray():DB::table('importpdfs')->get()runs the query and returns a Laravel Collection, which does support thetoArray()method. - Added a
returnstatement: You need to return the download response so Laravel knows to send the Excel file to the user's browser. - Simplified the final download call: The third parameter in
Excel::download()lets you define the filename directly, so you don't need the extra->download('xlsx')at the end.
Bonus: Cleaned-Up Version (Using Collection Methods)
If you want to trim down the code, you can use Laravel's collection helper methods to build your export array without a manual foreach loop:
function excel() { $header = ['Battery', 'No_of_questions_attempted', 'SAS', 'NPR', 'ST', 'GR']; $pdf_data = DB::table('importpdfs')->get() ->map(function($pdf) { return [ $pdf->Battery, $pdf->No_of_questions_attempted, $pdf->SAS, $pdf->NPR, $pdf->ST, $pdf->GR ]; }) ->prepend($header) ->toArray(); return Excel::download('Pdf Data', function ($excel) use ($pdf_data) { $excel->setTitle('Pdf Data'); $excel->sheet('Pdf Data', function ($sheet) use ($pdf_data) { $sheet->fromArray($pdf_data, null, 'A1', false, false); }); }, 'pdf_data.xlsx'); }
内容的提问来源于stack exchange,提问作者pro
相关产品推荐
相关产品推荐

