2

I have 2 endpoints:

  1. This one for filter data

    • /api/v1/admin/sale-product?status=success&category=something
  2. So, after I filtered it I want to export those data as csv file by below endpoint:

    • /api/v1/admin/sale-detail/export
  3. If my data isn't filtered It will export all data.

How can I do it? I'm using Laravel Excel Any suggestion? Please help me!!!

My Controller:

<?php

namespace App\Http\Controllers\Backend;

use App\Exports\SaleDetailExport;
use App\Http\Controllers\Controller;
use App\Http\Resources\SaleDetailReportCollection;
use App\Repositories\Interfaces\SaleProductRepositoryInterface;
use Maatwebsite\Excel\Facades\Excel;

class SaleProductController extends Controller
{
    protected $saleProduct;

    /**
     * Initilize sale product repository
     * 
     * @param SaleProductRepositoryInterface $saleProduct
     * 
     * @return void
     */
    public function __construct(
        SaleProductRepositoryInterface $saleProduct
    ) {
        $this->saleProduct = $saleProduct;
    }

    public function export()
    {
        return Excel::download(new SaleDetailExport, 'sale_detail.csv');
    }
}

My SaleDetailExport :

<?php

namespace App\Exports;

use App\Models\SaleDetail;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class SaleDetailExport implements FromCollection, WithHeadings, WithMapping
{
    public function headings(): array
    {
        return [
            '#',
            'Price',
            'Quantity',
            'Sale Date',
            'Product Name',
            'Category',
            'Sub-Category',
            'Status',
        ];
    }

    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return SaleDetail::with(['product'])
        ->with(['product.categoryWithTrash'])
        ->with(['product.categoryWithTrash.parentedWithTrash'])
        ->get();
    }

    public function map($saleDetail) : array 
    {
        return [
            $saleDetail->id,
            $saleDetail->price,
            $saleDetail->quantity,
            $saleDetail->created_at,
            $saleDetail->product->title,
            $saleDetail->product->categoryWithTrash->title,
            $saleDetail->product->categoryWithTrash->parentedWithTrash->title,
            $saleDetail->ret = getConstant('ret_statuses.' . $saleDetail->ret),
        ];
    }
}

Chantha
  • 27
  • 6

0 Answers0