Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Sharim's avatar

Export Products in Excel & PDF by category

I'm exporting all products in excel. Its working. But I can't export in pdf. Moreover I want to export by category. But I don't know how to do it.

ProductsExport:

<?php

namespace App\Exports;

use App\Product;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;

class ProductsExport implements FromCollection, WithHeadings, WithEvents
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        $products = Product::select(
            'name', 'code', 'price', 'slug', 'details', 'ecommerce', 'quantity',
            'description', 'created_at', 'category_id', 'origin', 'warranty')->get();
        $category = $products->tags;
        return $category;
    }

    public function map($products)
    {
        return [
            $products->code,
            $products->tags->name,
            Date::dateTimeToExcel($products->created_at),
        ];
    }

    public function headings(): array
    {
        return [
            'Name',
            'Product Code',
            'Price',
            'Slug',
            'Details',
            'E-commerce',
            'Quantity', 'Description', 'Created_at', 'Category_id', 'Origin', 'Warranty',
        ];
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function registerEvents(): array
    {
        return [
            AfterSheet::class    => function(AfterSheet $event) {
   
                // $event->sheet->getDelegate()->getRowDimension('1')->setRowHeight(40);
                $event->sheet->getDelegate()->getColumnDimension('A')->setWidth(50);
                $event->sheet->getDelegate()->getColumnDimension('B')->setWidth(10);
                $event->sheet->getDelegate()->getColumnDimension('D')->setWidth(50);
                $event->sheet->getDelegate()->getColumnDimension('E')->setWidth(50);
                $event->sheet->getDelegate()->getColumnDimension('F')->setWidth(5);
                $event->sheet->getDelegate()->getColumnDimension('H')->setWidth(50);
                $event->sheet->getDelegate()->getColumnDimension('I')->setWidth(20);
                $event->sheet->getDelegate()->getColumnDimension('K')->setWidth(10);
            },
        ];
    }
}

Controller:

public function export() {
        // return (new ProductsExport)->download('products.pdf', Excel::DOMPDF);

        return Excel::download(new ProductsExport, 'products.xlsx');  //Working
    }

Product Model:

public function tags() {
        return $this->belongsToMany('App\Tag');
    }
0 likes
0 replies

Please or to participate in this conversation.