How to pass a part of Laravel Eloquent query to method

Viewed 159

I want to use the different queries inside one method and I want to pass a part of query inside that.

My method looks like this:

static function methodName($partOfQuery)
{
   ModelName::where('...')->$partOfQuery->...;
}

And I want to do something like:

$partOfQuery = where('columnName', '>=', 5)->whereRaw('Other Condition');
self::methodName($partOfQuery);

But I was faced with this error: Call to undefined function App\Classes\ClassName\where()

Anyone could help me with this issue? Thanks

2 Answers

I think that the error is because where is called without an eloquent model class.

Something you can do with query builder is to call a function inside your where condition like:

SomeModel::where(function($query){
// do something
$query->where(...)
})

I doubt there is nothing exactly like what you described. But there are alternatives, if I understand correctly, you are trying to chain multiple methods.

If so, you can do the following:

In your model class:

static function getActiveBooks()
{
    return self::where('status', 'active');
}
public function getFeaturedBooks() {
    return $this->getActiveBooks()->where('featured', 'active');
}

Usage:

$activeBooks = (new Book())->getFeaturedBooks()->get();

There are multiple ways, you can also use scope as @levi described in the comment section , they are 2 sides of the same coin.

Related