91 lines
2.7 KiB
PHP
91 lines
2.7 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Http\Controllers\Api\V1;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Http\Requests\Api\V1\ClientRequest;
|
|
use App\Http\Resources\ClientResource;
|
|
use App\Models\Client;
|
|
use App\Support\TranslatablePayload;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
|
|
|
/**
|
|
* The organisations the work was for, as the panel edits them.
|
|
*/
|
|
class ClientController extends Controller
|
|
{
|
|
protected const WITH = ['logoMedia'];
|
|
|
|
/**
|
|
* Filters: is_public, search (name), trashed.
|
|
*/
|
|
public function index(Request $request): AnonymousResourceCollection
|
|
{
|
|
$this->authorize('viewAny', Client::class);
|
|
|
|
$clients = Client::query()
|
|
->with(self::WITH)
|
|
->withCount('projects')
|
|
->when($request->has('is_public'), fn ($q) => $q->where('is_public', $request->boolean('is_public')))
|
|
->when($request->filled('search'), fn ($q) => $q->where('name', 'like', '%'.$request->string('search').'%'))
|
|
->when($request->boolean('trashed'), fn ($q) => $q->onlyTrashed())
|
|
->orderBy('position')
|
|
->orderBy('name')
|
|
->paginate(perPage: min($request->integer('per_page', 25), 100))
|
|
->withQueryString();
|
|
|
|
return ClientResource::collection($clients);
|
|
}
|
|
|
|
public function store(ClientRequest $request): JsonResponse
|
|
{
|
|
$this->authorize('create', Client::class);
|
|
|
|
return ClientResource::make($this->save(new Client, $request))->response()->setStatusCode(201);
|
|
}
|
|
|
|
public function show(Client $client): ClientResource
|
|
{
|
|
$this->authorize('view', $client);
|
|
|
|
return ClientResource::make($client->load(self::WITH)->loadCount('projects'));
|
|
}
|
|
|
|
public function update(ClientRequest $request, Client $client): ClientResource
|
|
{
|
|
$this->authorize('update', $client);
|
|
|
|
return ClientResource::make($this->save($client, $request));
|
|
}
|
|
|
|
public function destroy(Client $client): JsonResponse
|
|
{
|
|
$this->authorize('delete', $client);
|
|
|
|
$client->delete();
|
|
|
|
return response()->json(status: 204);
|
|
}
|
|
|
|
public function restore(Client $client): ClientResource
|
|
{
|
|
$this->authorize('restore', $client);
|
|
|
|
$client->restore();
|
|
|
|
return ClientResource::make($client->load(self::WITH)->loadCount('projects'));
|
|
}
|
|
|
|
protected function save(Client $client, ClientRequest $request): Client
|
|
{
|
|
$client->fill(TranslatablePayload::merge($client, $request->validated(), $client->translatable));
|
|
$client->save();
|
|
|
|
return $client->load(self::WITH)->loadCount('projects');
|
|
}
|
|
}
|