1

I have the following base query I use for retrieving collections with their relations, scopes, sorting, filtering,... This base query is used on almost all my models by extending the class this base query is in.

        return $this->runSortQuery(
            $query->when($request->has('filter'),
                function($query) use ($request) {
                    return $query->search($request->filter);
                }
            )->when($request->has('with'), 
                function($query) use ($request) {
                    return $query->with(
                        explode(',', $request->with)
                    );
                }
            )->when($request->has('scopes'),
                function($query) use ($request) {
                    return $query->scopes(
                        json_decode($request->scopes, true)
                    );
                }
            ) /* and so on... */, $request
        )->paginate((isset($request->paginate)) ? $request->paginate : 15);

Is it possible to replace the callback in every when with a custom function call? The reason I want this is because this base function is getting really long and I would like the method in the callback in it's own function, for readability and to keep this maintainable.

I tried this, but this obviously does not work.

$query->when($request->has('filter'), $this->filter($query, $request->filter))
      ->when($request/* and so on... */);

Can this be done in another way or what would be a good pattern or method to do this?

Odyssee
  • 2,393
  • 2
  • 19
  • 38
  • 1
    This package (yep its made by me) could help you https://github.com/Kyslik/laravel-filterable; other than that I can not really understand what you want to achieve. Perhaps use proper [query scopes](https://laravel.com/docs/5.7/eloquent#query-scopes)? – Kyslik Oct 10 '18 at 14:30
  • I simply want to extract the callback to a seperate function. Replace `function($query) use ($x) {...}` with for exapmle $this->methodName($q, $x)` to keep my base method as clean as possible. But as expected `$q` is undefined when you call it like `$this->someMethodName($q, $x)`. I've been reading a lot to find a solution, my guess is that this cannot be done, but I've stumbeled onto something usable for this situation, I will keep this updated if I find something that works. – Odyssee Oct 10 '18 at 14:43

1 Answers1

1

Yes, you can use the callables like so:

$query->when($request->has('filter'), [$this, 'someMethodNameInClass'])
    ->...

Check out this SO thread to learn more

Paras
  • 9,258
  • 31
  • 55