'id', 'sort' => 'DESC']) { return Transformation::when(array_keys($filter, true), function ($query) use ($filter) { if (!empty($filter['name'])) { $query->where('name', 'like', '%' . $filter['name'] . '%'); } }) ->orderBy($sort['by'], $sort['sort']) ->paginate($perPage ?: env('PAGE_LIMIT', 999)); } /** * */ public function findById($id) { return Transformation::where('id', $id)->first(); } /** * */ public function create(array $data) { $result = false; DB::beginTransaction(); try { if (isset($data['before'])) { $data['before'] = $this->upload($data['before']); } if (isset($data['after'])) { $data['after'] = $this->upload($data['after']); } $result = Transformation::create($data); if ($result) { DB::commit(); } } catch (\Throwable $th) { report($th); DB::rollback(); } return $result; } /** * */ public function update($id, array $data) { $result = false; DB::beginTransaction(); try { $model = $this->findById($id); $oldBefore = $model->before; $oldAfter = $model->after; if (isset($data['before'])) { if (!is_null($oldBefore)) { $this->remove($oldBefore); } $data['before'] = $this->upload($data['before']); } if (isset($data['after'])) { if (!is_null($oldAfter)) { $this->remove($oldAfter); } $data['after'] = $this->upload($data['after']); } $result = $model->update($data); if ($result) { DB::commit(); } } catch (\Throwable $th) { report($th); DB::rollback(); } return $result; } /** * */ public function delete($id) { $result = false; DB::beginTransaction(); try { $model = $this->findById($id); $oldBefore = $model->before; $oldAfter = $model->after; $result = $model->delete(); if ($result) { $this->remove($oldBefore); $this->remove($oldAfter); DB::commit(); } } catch (\Throwable $th) { report($th); DB::rollback(); } return $result; } /** * */ public function upload($file) { $fileExtension = $file->getClientOriginalExtension(); $fileName = 'IMG' . time() . '_' . uniqid() . '.' . $fileExtension; $file->move(storage_path() . '/app/public/' . Transformation::FILE_PATH, $fileName); return $fileName; } /** * */ public function remove($fileName) { $fullFilePath = storage_path() . '/app/public/' . Transformation::FILE_PATH . $fileName; if (file_exists($fullFilePath)) { unlink($fullFilePath); } return true; } }