9

Concept Problem: I have a very simple problem when using the touches attribute, to automatically update timestamp on a depending model; it correctly does so but also applies the global scopes.

Is there any way to turn this functionality off? Or to ask specifically for automatic touches to ignore global scopes?


Concrete Example: When an ingredient model is updated all related recipes should be touched. This works fine, except we have a globalScope for separating the recipes based on locales, that also gets used when applying the touches.


Ingredient Model:

class Ingredient extends Model
{
    protected $touches = ['recipes'];

    public function recipes() {
        return $this->belongsToMany(Recipe::class);
    }

}

Recipe Model:

class Recipe extends Model
{
    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope(new LocaleScope);
    }

    public function ingredients()
    {
        return $this->hasMany(Ingredient::class);
    }
}

Locale Scope:

class LocaleScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $locale = app(Locale::class);

        return $builder->where('locale', '=', $locale->getLocale());
    }

}
Nicklas Kevin Frank
  • 6,079
  • 4
  • 38
  • 63

2 Answers2

28

If you want to explicitly avoid a global scope for a given query, you may use the withoutGlobalScope() method. The method accepts the class name of the global scope as its only argument.

$ingredient->withoutGlobalScope(LocaleScope::class)->touch();
$ingredient->withoutGlobalScopes()->touch();

Since you're not calling touch() directly, in your case it will require a bit more to make it work.

You specify relationships that should be touched in model $touches attribute. Relationships return query builder objects. See where I'm going?

protected $touches = ['recipes'];

public function recipes() {
   return $this->belongsToMany(Recipe::class)->withoutGlobalScopes();
}

If that messes with the rest of your application, just create a new relationship specifically for touching (heh :)

protected $touches = ['recipesToTouch'];

public function recipes() {
   return $this->belongsToMany(Recipe::class);
}

public function recipesToTouch() {
   return $this->recipes()->withoutGlobalScopes();
}
Choxx
  • 945
  • 1
  • 24
  • 46
Tadas Paplauskas
  • 1,863
  • 11
  • 15
-3

You can define a relationship in the model and pass parameters to it like following:

public function recipes($isWithScope=true)
{
    if($isWithScope)
        return $this->belongsToMany(Recipe::class);
    else
        return $this->recipes()->withoutGlobalScopes();
}

then use it like this recipes->get(); and recipes(false)->get();

Rana Hyder
  • 363
  • 2
  • 10