Files
aroginhealthcare/Modules/Post/app/Repositories/PostRepository.php
2025-08-17 16:23:14 +05:45

151 lines
3.3 KiB
PHP

<?php
namespace Modules\Post\app\Repositories;
use Modules\Post\app\Models\Post;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
class PostRepository
{
/**
*
*/
public function findAll($perPage=null, $filter=[], $sort=['by'=>'id', 'sort'=>'DESC'])
{
return Post::when(array_keys($filter, true), function ($query) use ($filter) {
if (!empty($filter['page_id'])) {
$query->where('page_id', $filter['page_id']);
}
})
->orderBy($sort['by'], $sort['sort'])
->paginate($perPage ?: env('PAGE_LIMIT', 999));
}
/**
*
*/
public function findBySlug($slug)
{
return Post::where('slug', $slug)->first();
}
/**
*
*/
public function findById($id)
{
return Post::where('id', $id)->first();
}
/**
*
*/
public function create(array $data)
{
$result = false;
DB::beginTransaction();
try {
if(isset($data['image'])) {
$data['image'] = $this->upload($data['image']);
}
$result = Post::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);
$oldImage = $model->image;
if(isset($data['image'])) {
if (!is_null($oldImage)) {
$this->remove($oldImage);
}
$data['image'] = $this->upload($data['image']);
}
$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);
$oldImage = $model->image;
$result = $model->delete();
if($result) {
$this->remove($oldImage);
DB::commit();
}
} catch (\Throwable $th) {
report($th);
DB::rollback();
}
return $result;
}
/**
*
*/
public function upload($file)
{
$fileExtension = $file->getClientOriginalExtension();
$fileName = 'IMG' . time() . '.' . $fileExtension;
$file->move(storage_path() . '/app/public/' . Post::FILE_PATH, $fileName);
return $fileName;
}
/**
*
*/
public function remove($fileName)
{
$fullFilePath = storage_path() . '/app/public/' . Post::FILE_PATH . $fileName;
if (file_exists($fullFilePath)) {
unlink($fullFilePath);
}
return true;
}
}