惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Check Point Blog
Y
Y Combinator Blog
GbyAI
GbyAI
Microsoft Azure Blog
Microsoft Azure Blog
Martin Fowler
Martin Fowler
博客园_首页
大猫的无限游戏
大猫的无限游戏
美团技术团队
S
SegmentFault 最新的问题
T
The Blog of Author Tim Ferriss
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
MyScale Blog
MyScale Blog
小众软件
小众软件
Vercel News
Vercel News
阮一峰的网络日志
阮一峰的网络日志
N
Netflix TechBlog - Medium
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
量子位
博客园 - 【当耐特】
J
Java Code Geeks
F
Fortinet All Blogs
宝玉的分享
宝玉的分享
Stack Overflow Blog
Stack Overflow Blog
博客园 - 司徒正美

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Multiple Sheets Excel Export in Laravel
Rafli Zocky · 2026-05-11 · via DEV Community
Cover image for Multiple Sheets Excel Export in Laravel

Rafli Zocky

This example uses the maatwebsite/excel package.

composer require maatwebsite/excel:^3.1

Enter fullscreen mode Exit fullscreen mode

1. Route

Route::get('/export-excel', [App\Http\Controllers\MyController::class, 'excel'])->name('export-excel');

Enter fullscreen mode Exit fullscreen mode

2. Simple View

Date input and a button that triggers the download.

<div class="mb-4 form-group col-lg-4">
    <label class="form-label">Start Date</label>
    <input type="text" name="start_date" id="start_date" class="form-control" required>
</div>
<div class="mb-4 form-group col-lg-4">
    <label class="form-label">End Date</label>
    <input type="text" name="end_date" id="end_date" class="form-control" required>
</div>

<button type="button" class="btn btn-primary exportExcel">Excel</button>

$(document).on('click', '.exportExcel', function() { 
  var start = $('#start_date').val(); 
  var end = $('#end_date').val(); 

  window.location.href = {{ route('export-excel') }}?start=${start}&end=${end}; 
});

Enter fullscreen mode Exit fullscreen mode

3. Controller

Note: if the query is taking long, then its better to separate the sheets. Just create separate files and try to use FromQuery and WithChunkReading.

use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Excels\Exports\MyExport;
use Illuminate\Support\Facades\DB;

class MyController extends Controller
{
    public function excel(Request $request)
    {
        $start = $request->start_date;
        $end = $request->end_date;

        // Sheet 1
        $sheet1 = DB::table('users')
            ->select('name','email')
            ->whereBetween('created_at', [$start, $end])
            ->get()
            ->map(fn($r) => [$r->name, $r->email]);

        // Sheet 2
        $sheet2 = DB::table('orders')
            ->select('invoice','total')
            ->whereBetween('created_at', [$start, $end])
            ->get()
            ->map(fn($r) => [$r->invoice, $r->total]);

        return Excel::download(new MyExport($sheet1, $sheet2), 'report.xlsx');
    }
}

Enter fullscreen mode Exit fullscreen mode

4. Export (Multiple Sheets)

namespace App\Excels\Exports;

use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use App\Excels\Exports\Sheets\MySheet;

class MyExport implements WithMultipleSheets
{
    public function __construct(
        protected $sheet1,
        protected $sheet2
    ) {}
    public function sheets(): array
    {
        return [
            new MySheet($this->sheet1, 'Users'),
            new MySheet($this->sheet2, 'Orders'),
        ];
    }
}

Enter fullscreen mode Exit fullscreen mode

5. Sheet Class

Each instance represents one Excel tab.

namespace App\Excels\Exports\Sheets;

use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithTitle;
use Illuminate\Support\Collection;
class MySheet implements FromArray, WithTitle
{
    public function __construct(
        protected $data,
        protected $title
    ) {}

    public function array(): array
    {
        if ($this->title === 'Users') {
            return [
                ['NAME', 'EMAIL'],
                ...$this->data->toArray(),
            ];
        }

        return [
            ['INVOICE', 'TOTAL'],
            ...$this->data->toArray(),
        ];
    }

    public function title(): string
    {
        return $this->title;
    }
}

Enter fullscreen mode Exit fullscreen mode

Need help building your app? I’m available for freelance web & Android development — raflizocky.netlify.app

☕ Support my writing: paypal.me/raflizocky · saweria.co/raflizocky