Skip to content
Advertisement

Avoid laravel global scope on specific queries

I have a stuents tablle with 3 columns graduated , leaver and deleted_at.

graduated and leaver are int (1) with null as default value. When a student graduates or leaves the school, the corresponding columns becomes 1.

When i use

$students=Student::get();

I need to only return Student where graduated and leaver are null, so I create two global scopes:

protected static function boot()
{
    parent::boot();

     static::addGlobalScope('onlyGraduated', function ($builder) {
        $builder->where('graduated', null);
    });
    static::addGlobalScope('onlyLeaver', function ($builder) {
        $builder->where('leaver', null);
    }); 
}

This works for most use cases, but what should I do for some specific queries when I want the students thar are graduated? such as

Students::where("graduated",1)->get();

Advertisement

Answer

If you need to avoid a global scope in a specific query, yuu should use withoutGlobalScope:

Students::withoutGlobalScope('onlyGraduated')->where("graduated",1)->get();

I would create a local scope in your Model called graduated and leaver:

public function scopeGraduated($query) {
  return $query->withoutGlobalScope('onlyGraduated')->where("graduated",1);
}

public function scopeLeavers($query) {
  return $query->withoutGlobalScope('onlyLeaver')->where("leaver",1);
}

Then you will be able to query the data using:

Students::get(); // Only students with both graduated and leaver null
Students::graduated()->get(); // Students with leaver null and graduated 1
Students::leavers()->get(); // Students with leaver 1 and graduated null
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement