Use Laravel touches without global scopes
Asked Answered
M

2

10

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

}
Moscow answered 14/9, 2016 at 12:53 Comment(0)
Z
30

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();
}
Zedoary answered 14/9, 2016 at 13:18 Comment(0)
D
-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();

Dental answered 31/1, 2022 at 12:1 Comment(1)
And how do you pass a parameter through the touches attribute? Without this key information, this is not a solution.Moscow

© 2022 - 2024 — McMap. All rights reserved.