Ali
Ali

Reputation: 669

Get Undefined method name exception in repository design pattern in laravel ( Call to undefined method Illuminate\Database\Eloquent\Builder)

I have a repository that have this function inside it:

class MyRepository {

    public function findWhere(string $column, $operator = '=', $value = null)
    {
        return $this->entity->where($column, $operator, $value);
    }
}

Now in my controller, I want to use it to have many where functions:

for example this query :

Model::where('id','=',2)->where('name' , '=' , 'test')->get() 

= 
$repository = app(MyRepository::class);

$repository->findWhere('id', '=', 2)
            ->findWhere('name', '=', 'test')
            ->get();

but I get following error after running the above code:

Call to undefined method Illuminate\Database\Eloquent\Builder::findWhere()

Upvotes: 0

Views: 251

Answers (1)

Ali
Ali

Reputation: 669

I find the solution

we can have another method in Repository class that just add conditions and return $this.

for example:


public function chainWhere($column, $value)
{
   $this->entity->where($column, $value);

   return $this;
}

Now in controller we can have any number of where conditions that we want

just for latest where condition we should use findWhere because we need Builder object to have result for example:

 $repository
      ->chainWhere('id', '=', 2)
      ->chainWhere('condition2', '=', 20)
      ->chainWhere('condition3', '=', 30)   
      ->findWhere('name', '=', 'test')
      ->get();


Upvotes: 0

Related Questions