z-song / laravel-admin

Build a full-featured administrative interface in ten minutes
https://laravel-admin.org
MIT License
11.15k stars 2.81k forks source link

How to link Search results and CSV rows on Laravel Excel v3? #3363

Closed yano3nora closed 5 years ago

yano3nora commented 5 years ago

Versions

Description:

Hello. Thank you for your wonderful package.

Ask questions about exporting data using Laravel Excel.

When using customized ExcelExporter for CSV output as shown below, it seems that search condition is not linked to CSV result.

// In grid() method.
$grid->exporter(new \App\Admin\Extensions\UsersExporter());

Since I wanted to link search results with CSV like the standard CSV output function of laravel-admin, I came up with a method to use ExcelExpoter::getData(false) and fromCollection Concern of Laravel Excel.

However, because ExcelExporter originally implements fromQuery , the output will be doubled.

Overriding ExcelExporter::query() , the following implementation was implemented by trial and error so that the query to be returned is given the search condition from the Grid screen.

// UsersExpoter
namespace App\Admin\Extensions;

use Encore\Admin\Grid\Exporters\ExcelExporter;

class UsersExporter extends ExcelExporter
{
    protected $fileName = 'users.csv';
    protected $columns = [
        'id'   => 'ID',
        'name' => 'Name',
    ];

    public function query() {
        $filter     = $this->grid->getFilter();
        $conditions = $filter->conditions();
        $scope      = [];
        if ($sc = $filter->getCurrentScope()) {
            $scope = $sc->condition();
        }
        $model = $filter->getModel();
        $query = $model->addConditions(array_merge($conditions, $scope))->getQueryBuilder();
        if (!empty($this->columns)) {
            $columns = array_keys($this->columns);
            $eagerLoads = array_keys($this->getQuery()->getEagerLoads());
            $columns = collect($columns)->reject(function ($column) use ($eagerLoads) {
                return \Illuminate\Support\Str::contains($column, '.') || in_array($column, $eagerLoads);
            });
            return $query->select($columns->toArray());
        }
        return $query;
    }
}

The above looks like "search results and CSV output" are linked as I expected, but I am wondering if it is the "right way".

Could you tell me if there is another good way? Thank you for reading.

stale[bot] commented 5 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.