aiblog/app/Services/PostService.php
2024-11-17 11:30:01 +08:00

55 lines
No EOL
1.4 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Services;
use App\Models\Post;
use App\Models\User;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
class PostService
{
public function getPosts(array $filters = []): LengthAwarePaginator
{
$query = Post::with(['author:id,name', 'category:id,name']);
$query = $this->applyFilters($query, $filters);
return $query->latest()->paginate(10);
}
public function createPost(User $user, array $data): Post
{
return $user->posts()->create($data);
}
public function updatePost(Post $post, array $data): Post
{
$post->update($data);
return $post->fresh();
}
protected function applyFilters(Builder $query, array $filters): Builder
{
if (!empty($filters['author_id'])) {
$query->where('author_id', $filters['author_id']);
}
if (!empty($filters['category'])) {
$query->whereHas('category', function ($q) use ($filters) {
$q->where('name', $filters['category']);
});
}
if (!empty($filters['search'])) {
$query->where(function ($q) use ($filters) {
$q->where('title', 'like', "%{$filters['search']}%")
->orWhere('content', 'like', "%{$filters['search']}%");
});
}
return $query;
}
}