Customising Exports for the ‘Laravel Nova Excel’ Package

I recently worked on a project that needed an export for an Orders view within a Laravel Nova panel. If you have simple requirements, for example, exporting all fields with titles – that is relatively simple to produce. However, I needed to update fields and merge others with some other custom changes.

~

I recently worked on a project that needed an export for an Orders view within a Laravel Nova panel. If you have simple requirements, for example, exporting all fields with titles – that is relatively simple to produce. However, I needed to update fields and merge others with some other custom changes.

In short, I moved the export logic into its own Laravel Nova action called ExportOrders. and added this into the Nova Resource actions like so:

<?php
namespace App\Nova;

use App\Nova\Actions\ExportOrders;

class Order extends Resource
{
    // snipped..
    /**
     * Get the actions available for the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function actions(Request $request)
    {
        return [
            (new ExportOrders())
        ];
    }
}

Next, I created the above-named file at app/Nova/Actions/ExportOrders.php to define the headings and map the fields to their corresponding export fields:

<?php
namespace App\Nova\Actions;

use App\Models\Order;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\LaravelNovaExcel\Actions\DownloadExcel;

class ExportOrders extends DownloadExcel implements WithMapping, WithHeadings
{
    /**
     * @return array
     */
    public function headings(): array
    {
        return [
            'internal_order_id',
            'created_at',
            'stripe_transaction_id',
            'buyer_name',
            'buyer_email',
            'billing_address',
            'delivery_name',
            'delivery_address',
            'giftcard_amount',
            'total_paid',
            'message',
            'status'
        ];
    }

    /**
     * @param $order
     *
     * @return array
     */
    public function map($order): array
    {
        return [
            $order->id,
            $order->created_at,
            $order->transaction_id,
            $order->buyer_name,
            $order->buyer_email,
            $order->billing_address,
            $order->recipient_name,
            $order->delivery_address,
            $order->amount,
            $order->total,
            $order->notes,
            $order->status
        ];
    }
}

Initially I’d added more functionality within this class to merge fields and add custom export but in the end, I decided to move a lot of these field customisations into Eloquent accessors instead. This meant that when they were accessed in the Nova panel, exports or anywhere else they became consistent.