Skip to content

Commit b37b8ea

Browse files
committed
feat: implement filtering and sorting on CourseController
- add locations GET endpoint to give possible cities - install laravel-query-builder - add filtering and sorting to GET Course endpoint
1 parent 460782a commit b37b8ea

File tree

4 files changed

+160
-7
lines changed

4 files changed

+160
-7
lines changed

app/Http/Controllers/CourseController.php

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,25 @@
99
use App\Models\Course;
1010
use App\Services\CourseService;
1111
use Illuminate\Http\Response;
12+
use Spatie\QueryBuilder\AllowedFilter;
13+
use Spatie\QueryBuilder\QueryBuilder;
1214

1315
class CourseController extends Controller
1416
{
1517
public function __construct(protected CourseService $courseService) {}
1618

1719
public function index(): CourseCollection
1820
{
19-
return new CourseCollection(
20-
Course::query()
21-
->with(['school', 'category'])
22-
->paginate()
23-
);
21+
$courses = QueryBuilder::for(Course::class)
22+
->allowedFilters(AllowedFilter::partial('school.name'),
23+
AllowedFilter::exact('school.city'),
24+
AllowedFilter::exact('category.name')
25+
)
26+
->allowedSorts(['price', 'start_date'])
27+
->with(['school', 'category'])
28+
->paginate(10);
29+
30+
return new CourseCollection($courses);
2431
}
2532

2633
public function store(StoreCourseRequest $request): CourseResource
@@ -44,4 +51,14 @@ public function destroy(Course $course): Response
4451

4552
return response()->noContent();
4653
}
54+
55+
public function locations()
56+
{
57+
$cities = Course::query()
58+
->join('schools', 'courses.school_id', '=', 'schools.id')
59+
->distinct()
60+
->pluck('schools.city');
61+
62+
return response()->json($cities);
63+
}
4764
}

composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@
1010
"laravel/framework": "^11.9",
1111
"laravel/sanctum": "^4.0",
1212
"laravel/socialite": "^5.16",
13-
"laravel/tinker": "^2.9"
13+
"laravel/tinker": "^2.9",
14+
"spatie/laravel-query-builder": "^6.3"
1415
},
1516
"require-dev": {
1617
"fakerphp/faker": "^1.23",

composer.lock

Lines changed: 135 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

routes/api.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
})->middleware('auth:sanctum');
2727

2828
Route::apiResource('/courses', CourseController::class)->except('update');
29+
Route::get('/courses-locations', [CourseController::class, 'locations']);
2930

3031
Route::post('login', [AuthController::class, 'login']);
3132
Route::post('register', [AuthController::class, 'register']);

0 commit comments

Comments
 (0)