I have a query builder that returns paginated data:
$builder = Example::latest();
$examples = $builder->with([
'activity',
'followers',
'messages',
'assignedTeam',
'domain',
'history'])
->paginate();
return response()->json($examples);
The model has an accessor, isRelativeTo
that is a boolean value. I want to filter this by !isRelativeTo
. I know I can't map over it or add a filter directly, as it's not a collection, so wondering what the correct way of doing something like this might?
Here is my accessor logic:
public function getIsRelativeAttribute($value)
{
$user = auth('api')->user();
return $this->assigned_user_id == $user->id || $this->reported_by == $user->id
|| $user->teams()->where('id', $this->assigned_team_id)->exists();
}
I ended up creating scopes in addition to the accessor. In case anyone is curious:
/**
* Scope the query relative to the authenticated user
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param \App\User $user
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeRelativeTo($query, User $user)
{
$teamIDs = $user->teams->pluck('id');
$query->where('assigned_user_id', $user->id)
->orWhere('reported_by', $user->id)
->orWhereIn('assigned_team_id', $teamIDs);
}
/**
* Scope the query NOT relative to the authenticated user
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param \App\User $user
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeNotRelativeTo($query, User $user)
{
$teamIDs = $user->teams->pluck('id');
$query->where(function ($q) {
$user = auth('api')->user();
$q->whereNull('assigned_user_id')
->orWhere('assigned_user_id', '!=', $user->id);
})
->where('reported_by', '!=', $user->id)
->whereNotIn('assigned_team_id', $teamIDs);
}