Laravel-Nova-Excel icon indicating copy to clipboard operation
Laravel-Nova-Excel copied to clipboard

Access Filter Values In Fields Function

Open MannikJ opened this issue 4 years ago • 1 comments

Consider the following nova lense:

<?php

namespace App\Nova\Lenses;

use Illuminate\Http\Request;
use Laravel\Nova\Http\Requests\LensRequest;
use Laravel\Nova\Fields\Number;
use Maatwebsite\LaravelNovaExcel\Actions\DownloadExcel;
use App\Nova\Filters\Inventory\Date;

class Inventory extends Lens;
{
    public function fields(Request $request)
    {
       $date = ??? // Access the date filter value
        return [
            Number::make('Stock', 'stock')->resolveUsing(function () use ($date) {
                ...
                return $stock;
            }),
        ];
    }

    public function filters(Request $request)
    {
        return [
            new Date,
        ];
    }

    public function actions(Request $request)
    {
        return [
            (new DownloadExcel)->withHeadings()
        ];
    }
}

If the fields function is called by nova itself to form the index results the request object contains the active filters values. However if it is called from the DownloadExcel action, they are empty. I think this could be considered a bug. Or at least I would say it should be possible to access the filter values from within the fields function

Is there at least a quick workaround to get the filter values?

Please also see https://github.com/laravel/nova-issues/issues/2405

MannikJ avatar Mar 04 '20 10:03 MannikJ

This should help you:

public function calculate(NovaRequest $request)
    {
        $model = PaymentSystem::make();

        if ($request->has('filters')) {
            // Get the decoded list of filters
            $filters = json_decode(base64_decode($request->filters));

            foreach ($filters as $filter) {
                if (empty($filter->value)) {
                    continue;
                }

                // Create a new instance of the filter and apply the query to your model
                $model = (new $filter->class)->apply($request, $model, $filter->value);

oleksandr-roskovynskyi avatar Mar 04 '20 21:03 oleksandr-roskovynskyi