muzafferdede
4 months ago
678
6
Laravel

Any suggestions to improve this piece of code?

Posted 4 months ago by muzafferdede

Hi, i am not too happy with the way foreach works now. Is there any suggestions you guys can give me to improve it? I believe there could be many collection ways to do it. All i am trying to do is compare 2 arrays and if they match, call the method. Here is the code:

public function applyFiltersToModel($request, $model)
    {
        $request->range = optional($request)->range ?? 3600;
        $model = $model instanceof Builder ? $model : (new $model)->newQuery();

        $requestFilters = collect($request->all())->filter(function ($value, $key) {
            return class_exists($key);
        });

    // requestFilters will return array of filters such as 
    // 'App\Nova\Filters\Store' => 5
    // 'App\Nova\Filters\Date' => '2020-01-01'
    

    //$this->filters() will return array of filters such as
    // 0 => 'App\Nova\Filters\Store'
    // 1 => 'App\Nova\Filters\Date'

        foreach ($this->filters() as $filter) {
            foreach ($requestFilters as $requestFilter => $value) {
                if ($filter instanceof $requestFilter) {
                    $model = $filter->apply($request, $model, $value);
                }
            }
        }

        return $model;
    }

    public function filters()
    {
        return [
            new Store('sale'),
            new Date('sale_date', 'sale'),
        ];
    }

As you can see, i am trying to find out if the request contains any filter, if it's does, i call apply method of that filter.

Please sign in or create an account to participate in this conversation.