Skip to content

Commit 1e985b7

Browse files
committed
move Client visibleByEmployee logic from controller to model
1 parent 93d6a86 commit 1e985b7

File tree

3 files changed

+15
-9
lines changed

3 files changed

+15
-9
lines changed

app/Http/Controllers/Api/V1/ClientController.php

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
use App\Http\Resources\V1\Client\ClientResource;
1313
use App\Models\Client;
1414
use App\Models\Organization;
15-
use App\Models\Project;
1615
use Illuminate\Auth\Access\AuthorizationException;
1716
use Illuminate\Http\JsonResponse;
1817
use Illuminate\Support\Carbon;
@@ -47,13 +46,7 @@ public function index(Organization $organization, ClientIndexRequest $request):
4746
->orderBy('created_at', 'desc');
4847

4948
if (! $canViewAllClients) {
50-
$projectsQuery = Project::query()
51-
->whereBelongsTo($organization, 'organization')
52-
->visibleByEmployee($user)
53-
->distinct()
54-
->select('client_id');
55-
56-
$clientsQuery->whereIn('id', $projectsQuery);
49+
$clientsQuery->visibleByEmployee($user);
5750
}
5851

5952
$filterArchived = $request->getFilterArchived();

app/Models/Client.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use App\Models\Concerns\CustomAuditable;
88
use App\Models\Concerns\HasUuids;
99
use Database\Factories\ClientFactory;
10+
use Illuminate\Database\Eloquent\Builder;
1011
use Illuminate\Database\Eloquent\Casts\Attribute;
1112
use Illuminate\Database\Eloquent\Factories\HasFactory;
1213
use Illuminate\Database\Eloquent\Model;
@@ -62,6 +63,18 @@ public function projects(): HasMany
6263
return $this->hasMany(Project::class, 'client_id');
6364
}
6465

66+
/**
67+
* @param Builder<Client> $builder
68+
* @return Builder<Client>
69+
*/
70+
public function scopeVisibleByEmployee(Builder $builder, User $user): Builder
71+
{
72+
return $builder->whereHas('projects', function (Builder $builder) use ($user): Builder {
73+
/** @var Builder<Project> $builder */
74+
return $builder->visibleByEmployee($user);
75+
});
76+
}
77+
6578
/**
6679
* @return Attribute<bool, never>
6780
*/

tests/Unit/Endpoint/Api/V1/ClientEndpointTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ public function test_index_endpoint_returns_list_of_clients_assigned_to_employee
6262
{
6363
// Arrange
6464
$data = $this->createUserWithPermission([
65-
'clients:view'
65+
'clients:view',
6666
]);
6767

6868
$clients = Client::factory()->forOrganization($data->organization)->createMany(2);

0 commit comments

Comments
 (0)