authorize('viewAny', Project::class); $locale = app()->getLocale(); $projects = Project::query() ->with(self::WITH) ->when($request->filled('status'), fn ($q) => $q->where('status', $request->string('status'))) ->when($request->filled('search'), fn ($q) => $q->where("title->{$locale}", 'like', '%'.$request->string('search').'%')) ->when($request->boolean('trashed'), fn ($q) => $q->onlyTrashed()) ->orderBy('position') ->orderByDesc('created_at') ->paginate(perPage: min($request->integer('per_page', 25), 100)) ->withQueryString(); return ProjectResource::collection($projects); } public function store(ProjectRequest $request): JsonResponse { $this->authorize('create', Project::class); $project = $this->save(new Project, $request); return ProjectResource::make($project)->response()->setStatusCode(201); } public function show(Project $project): ProjectResource { $this->authorize('view', $project); return ProjectResource::make($project->load(self::WITH)); } public function update(ProjectRequest $request, Project $project): ProjectResource { $this->authorize('update', $project); return ProjectResource::make($this->save($project, $request)); } public function destroy(Project $project): JsonResponse { $this->authorize('delete', $project); $project->delete(); return response()->json(status: 204); } public function restore(Project $project): ProjectResource { $this->authorize('restore', $project); $project->restore(); return ProjectResource::make($project->load(self::WITH)); } /** * The record and its relations in one transaction: a project that saved * but lost its team halfway would be worse than one that did not save. */ protected function save(Project $project, ProjectRequest $request): Project { $data = $request->validated(); DB::transaction(function () use ($project, $data): void { $project->fill(TranslatablePayload::merge( $project, collect($data)->except(['technology_ids', 'service_ids', 'members'])->all(), $project->translatable, )); $project->save(); if (array_key_exists('technology_ids', $data)) { $project->technologies()->sync($data['technology_ids']); } if (array_key_exists('service_ids', $data)) { $project->services()->sync($data['service_ids']); } if (array_key_exists('members', $data)) { $project->members()->sync(collect($data['members'])->mapWithKeys( fn (array $member) => [$member['id'] => ['role' => $member['role'] ?? null]], )->all()); } }); return $project->load(self::WITH); } }