You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.4使用Maatwebsite/Excel导出Excel报错,求解决方案

Fixing the "Argument 1 passed to Builder::create() must be array, string given" Error in Laravel 5.4 Excel Export

Hey there, let's get this Excel export issue sorted out for you! That error message is pointing straight to the root of the problem—we're passing a non-array value to a method that strictly expects an array.

What's Causing the Error?

Your line $export = Student::all(); returns an Eloquent Collection object, not a plain PHP array. When you pass this collection directly to $sheet->fromArray(), the underlying code tries to process it as an array but ends up passing a mismatched type to Builder::create(), triggering that type error.

The Simple Fix

All we need to do is convert that Eloquent Collection into a native PHP array using the built-in toArray() method:

Corrected Full Code

// Convert the collection to a plain array first
$export = Student::all()->toArray();

Excel::create('Export Excel',function($excel) use($export){
    $excel->sheet('Sheet 1', function($sheet) use($export){
        $sheet->fromArray($export);
    });
})->download('xlsx');

Bonus: Customize Your Exported Fields

If you don't need every column from your students table in the export, you can specify exactly which fields to include before converting to an array—this makes your export cleaner and more efficient:

// Select only the fields you want to export, then convert to array
$export = Student::select('id', 'name', 'email', 'enrollment_date')->get()->toArray();

This adjustment ensures the fromArray() method gets the data format it needs, and you'll be able to download your Excel file without any errors.

内容的提问来源于stack exchange,提问作者JustMeNad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:32:13