I realise this is quite old, but thought this might help others who come across this question.
It might be better to refactor so that the partial query is added to an existing query via a method.
$query = ModelName::where('...');
$query = addPartOfQuery($query);
/* continue doing whatever else you need to do with the query, for example */
$models = $query->get();
The addPartOfQuery() method would then be something like this:
function addPartOfQuery($query) {
return $query->where('columnName', '>=', 5)->whereRaw('Other Condition');
}
Another possible approach would be to use a local scope in a trait that can be used by all models that need it.
trait PartOfQuery {
public function scopePartOfQuery(Builder $query): void {
$query->where('columnName', '>=', 5)->whereRaw('Other Condition');
}
}
In each model class that needs to use the partial query, you would need to use the trait.
class ModelName {
use PartOfQuery;
...
}
Your queries could then be written like this.
ModelName::partOfQuery()->where('...');
The trait approach only works if the partial query is always the same, regardless of the model. Otherwise, you could just add a separate scopes in each model, or use the first approach and add logic and additional parameters to the addPartOfQuery() method to handle any model-specific requirements.
To read more on local scopes, see https://laravel.com/docs/10.x/eloquent#local-scopes.