How to chain laravel model query builder

Viewed 272

I was extending laravel model scope query using :

public function newEloquentBuilder($query)
{
   return new FooBuilder($query);
}

public function newEloquentBuilder($query)
{
   return new BarBuilder($query);
}

class FooBuilder extends Builder
{
  public function joinBar()
  {
    return $this->leftJoin('bar', 'bar.id', '=', 'foo.id');
  }
}

class BarBuilder extends Builder
{
   public function whereActive()
   {
     return $this->where('is_active', true);
   }
}

Is it possible to chain laravel model query like this?

Foo::query()->joinBar()->Bar::query()->whereActive()->get()

Basically, I want to call a method in BarBuilder from FooBuilder, i dont want to add duplicate same method inside FooBuilder.

1 Answers

You might be overcomplicating this TBH. Take a look at Scopes:

https://laravel.com/docs/8.x/eloquent#local-scopes.

You should simply be able to define the following on Foo.php (Model):

public function scopeJoinBar($query){
  return $query->leftJoin('bar', 'bar.id', '=', 'foo.id');
}

public function scopeBarIsActive($query){
  return $query->where('bar.is_active', true);
}

Then you simply call these scopes:

$foos = Foo::joinBar()->barIsActive()->get();
Related