Yes, it is possible to apply a policy to a relationship. You can use the whereHas method to filter the relationship results based on the policy. Here's an example:
$events = Event::whereHas('users', function ($query) {
$query->where(function ($query) {
$query->where('id', 1)
->orWhere('id', 2);
});
})->get();
In this example, we're using the whereHas method to filter the users relationship based on the policy. The policy is defined as a closure that takes a query builder instance as its argument. We're using the where method to add a condition to the query builder that filters the users based on their ID. In this case, we're only retrieving users with an ID of 1 or 2.
You can replace the closure with a call to a policy method that returns a query builder instance. Here's an example:
$events = Event::whereHas('users', function ($query) {
$query->where(app(UserPolicy::class)->viewAny(Auth::user()));
})->get();
In this example, we're using the where method to add a condition to the query builder that filters the users based on the policy. We're calling the viewAny method on the UserPolicy class and passing in the authenticated user as an argument. The viewAny method returns a query builder instance that filters the users based on the policy.