Custom new query function in the model : I used protected $with = ['newQuery']; in model
public function newQuery(){
$query = parent::newQuery();
$query->where('slug','!=', "example");
return $query;
}
I want to disable this custom NewQuery function in the specific function. I used it without(newQuery) But it's not working,
You should not override newQuery()
. If you want to have a condition that runs with every single query you make (to that model) you should create a separate query scope
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class YourModel extends Model
{
protected static function booted(): void
{
static::addGlobalScope('filter-examples', function (Builder $builder) {
$builder->where('slug', '<>', 'example');
});
}
}
With this, you can define many global scopes. If you want to run a query without that scope, you can use the withoutGlobalScope(scope)
method
$results = YourModel::withoutGlobalScope('filter-examples')->get();