I would like to extend Eloquent Builder to have a support for search function. Inside my service provider I’ve added the following:
Builder::macro('search', function (string $searchBy) { ... }
which works. I can now call a search method on my model.
The issue I’m having is that the logic within it is getting a rather complex and I wouldn’t like it to be a single large script, however splitting to functions doesn’t work since scope when inside a macro
callback is actually from Eloquent Builder.
So this doesn’t work:
public function foo() { dd('bar'); } public function boot() { Builder::macro('search', function (string $searchBy) { $this->bla(); ... } }
Is there a way to use functions without going over the hassle of extending complete Eloquent Builder?
Advertisement
Answer
I have ended up creating a class which would contain the complete logic I need. I see this as a fairly good OOP practice.
Builder::macro('search', function (array $input) { $jsonQuery = new JsonQuery($this, $input); $jsonQuery->search(); return $this; });
For anyone interested in details, you can check out my JSON search package.