Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Laravel touches without global scopes

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());
    }

}
like image 904
Nicklas Kevin Frank Avatar asked Sep 14 '16 12:09

Nicklas Kevin Frank


1 Answers

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();
}
like image 80
Tadas Paplauskas Avatar answered Oct 20 '22 14:10

Tadas Paplauskas