dmikam's avatar

BelongsToMany and globalScopes

In short - I would like to define global scope that would filter related instances by the value of the field in pivot table. I have defined the next relationship:

class Client extends Model {
	function promotions():BelongsToMany{
		return $this->belongsToMany(Promotion::class)
					->using(ClientPromotionPivot::class);
	}
}
class Promotion extends Model {
		// ...
}
class ClientPromotionPivotextends Pivot {
		protected $casts = [
				'active' => 'boolean'
		];
}

My idea is that by default, everywhare where I access $client->promotions - only active ones would appear:

$active_promotions = $client->promotions;

BUT, sometimes I need to access them all:

$all_promotions = $client->promotions()
			->withoutGlobalScope('active_promotions') // or something similar
			->get();

Also I have many more similar relationships in many models where the Pivot table has the field active to be filtered on. The problem is it seems that global scopes doesn't know anything about the pivot table.

P.S. : Please do not offer creating two separated relations - like all_promotions and active_promotions - I would like to avoid this. Also I don't want to write something similar to $client->promotions()->wherePivot('active') everywhere I access promotions.

To me it looks like a missing feature in Eloquent/Laravel. I found this Issue published recently, but there is no solution to it: github.com/laravel/framework/issues/48617

0 likes
2 replies
dmikam's avatar

@DhPandya Thank you for the suggestion, but while $builder->whereRelation(...) is really useful for me, I don't see how it may improve my situation.

Please or to participate in this conversation.