Added filters for projects

This commit is contained in:
Kamil Niemczycki 2022-02-16 14:18:56 +01:00
parent ad20678d7a
commit b831de63e4
3 changed files with 19 additions and 4 deletions

View File

@ -6,6 +6,7 @@ namespace App\Http\Controllers\Api;
use App\Repository\Interfaces\ProjectRepository; use App\Repository\Interfaces\ProjectRepository;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class ProjectController extends Controller class ProjectController extends Controller
{ {
@ -14,9 +15,17 @@ class ProjectController extends Controller
private ProjectRepository $projectRepository private ProjectRepository $projectRepository
) {} ) {}
public function index() public function index(Request $request)
{ {
return $this->projectRepository->all(); $request->validate([
'category' => 'nullable|string|exists:categories,slug'
]);
$filters = [];
if ($request->has('category') && ($category = $request->get('category')) !== '') {
$filters['category'] = $category;
}
return $this->projectRepository->all($filters);
} }
public function show(int $project) public function show(int $project)

View File

@ -11,7 +11,7 @@ use Illuminate\Support\Collection;
interface ProjectRepository interface ProjectRepository
{ {
public function all(): Collection; public function all(array $filters = []): Collection;
public function get(int $id): ProjectResource; public function get(int $id): ProjectResource;
public function update(Project $project, array $data = []): bool; public function update(Project $project, array $data = []): bool;
public function create(array $data = []): Project; public function create(array $data = []): Project;

View File

@ -8,6 +8,7 @@ use App\Http\Resources\ProjectCollection;
use App\Http\Resources\ProjectResource; use App\Http\Resources\ProjectResource;
use App\Models\Project; use App\Models\Project;
use App\Repository\Interfaces\ProjectRepository as ProjectRepositoryInterface; use App\Repository\Interfaces\ProjectRepository as ProjectRepositoryInterface;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
class ProjectRepository implements ProjectRepositoryInterface class ProjectRepository implements ProjectRepositoryInterface
@ -19,12 +20,17 @@ class ProjectRepository implements ProjectRepositoryInterface
private Project $project private Project $project
) {} ) {}
public function all(): Collection public function all(array $filters = []): Collection
{ {
$project = $this->project $project = $this->project
->query() ->query()
->orderBy('release_data', 'ASC'); ->orderBy('release_data', 'ASC');
foreach ($filters as $filter_name => $filter_value) {
if ($filter_name === 'category' && $filter_value !== 'all')
$project->where('categories', 'like', '%"'. $filter_value .'"%');
}
if (!$this->auth) if (!$this->auth)
$project->visibled(); $project->visibled();