Skip to content

Lens CSV export empty when query ID is not the same as resource model ID #4890

@moisessepulveda

Description

@moisessepulveda

Description:

When you we have a lens that contains a group by and you try to export data as CSV, it doesn't work when you select individual record. It only works when "Select all" is selected.

This issue only happens when primary key obtained from query does not belongs to the same model as resource.

Detailed steps to reproduce the issue on a fresh Nova installation:

First keep in mind and create the next two models:

Employee:

column type
id integer
name string

Payment:

column type
id integer
amount integer
employee_id integer
  • Create Resource for every model.
  • Create a lens that contains a group by. The primary key obtained from the query should come from another table different than resource one.
  • We will create a Payment Lens that will obtain how many payments every employee has. Something like this:
employee id name payments
1 jack sparrow 5
2 jane doe 10
3 jhon doe 20

Consider a query like this:

/**
     * Get the query builder / paginator for the lens.
     *
     * @param  \Laravel\Nova\Http\Requests\LensRequest  $request
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return mixed
     */
    public static function query(LensRequest $request, $query)
    {
        return $request->withOrdering($request->withFilters(
            $query->select('employees.id', 'employees.name', DB::raw('count(payments.id) as count'))
            ->join('employees', 'payments.employee_id', '=', 'employees.id')
            ->groupBy('employees.id', 'employees.name')
        ));
    }

fields:

public function fields(NovaRequest $request)
    {
        return [
            ID::make(__('ID'), 'id')->sortable(),
            Text::make('Name', 'name'),
            Number::make('Count', 'count')
        ];
    }

actions:

public function actions(NovaRequest $request)
    {
        return [
            ExportAsCsv::make(__('Exportar a CSV'))->withFormat(function ($model) {
                return [
                    'id' => $model->id,
                    'Name' => $model->name,
                    'Count' => $model->count,
                ];
            })
        ];
    }
  • IMPORTANT Add this LENS to Payment Resource.
  • Use exportAsCSV Facade exporting the related data.
  • Open Nova admin panel, then go to payment resource and open the lens just created.
  • Try to export individual record using Export as CSV action.
  • You will note that CSV actually is downloaded, but it completely empty.
  • If you try "Select all" and then try to export is works like a charm.

Metadata

Metadata

Assignees

No one assigned

    Labels

    pendingIssues that are pending triage

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions