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

Laravel 5.6调用Maatwebsite\Excel::create()报错求解决

解决 Laravel 5.6 中 Maatwebsite/Excel 的 Excel::create() 未定义方法错误

这个报错的核心原因很明确:你正在使用 Maatwebsite/Excel 3.0+ 版本,但create()方法是该扩展2.x版本的旧API,3.0+已经彻底移除了这个方法,改用全新的导出类机制。下面是一步步的修复方案:


第一步:确认你的扩展版本

先打开项目根目录的composer.json,找到maatwebsite/excel的版本号,如果是^3.0或者更高,就说明你用的是新版本,需要按新API修改代码。


第二步:创建自定义导出类

在终端执行Artisan命令生成一个导出类,适配你的学生数据场景:

php artisan make:export StudentsExport

这个命令会在app/Exports目录下生成StudentsExport.php文件。


第三步:修改导出类的逻辑

打开生成的StudentsExport.php,把你之前的视图加载逻辑迁移过来,通过构造函数传递所需数据:

<?php

namespace App\Exports;

use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;

class StudentsExport implements FromView
{
    protected $input;
    protected $subjects;
    protected $students;

    // 构造函数接收外部传递的数据
    public function __construct($input, $subjects, $students)
    {
        $this->input = $input;
        $this->subjects = $subjects;
        $this->students = $students;
    }

    // 实现FromView接口,返回要导出的视图
    public function view(): View
    {
        return view('app.excel', compact('subjects', 'input', 'students'));
    }
}

第四步:修改控制器代码

把原来的Excel::create()代码替换成新版本的调用方式:

use App\Exports\StudentsExport;
use Maatwebsite\Excel\Facades\Excel;

// 保留你原来的班级名称处理逻辑
$cl = ClassModel::Select('name')->where('code',$input->class)->first(); 
$input->class = $cl->name; 
$fileName = $input->class.'-'.$input->section.'-'.$input->session.'-'.$input->exam; 

// 新版本的导出调用
return Excel::download(new StudentsExport($input, $subjects, $students), $fileName.'.xlsx');

第五步:检查config/app.php的配置(可选)

如果你是手动配置的服务提供者和别名,确保是3.x版本的正确格式:

'providers' => [
    // ...
    Maatwebsite\Excel\ExcelServiceProvider::class,
],

'aliases' => [
    // ...
    'Excel' => Maatwebsite\Excel\Facades\Excel::class,
],

注意:Laravel 5.5+支持服务提供者自动发现,所以如果你的composer.json里extra.laravel.dont-discover没有排除这个扩展,其实可以不用手动配置这两项。


这样修改后,原来的导出逻辑就能正常运行了,新版本的API更符合Laravel的依赖注入和代码组织规范,也更易于维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:26:56