search and filtering

PHOTO EMBED

Sat Jan 20 2024 01:44:36 GMT+0000 (Coordinated Universal Time)

Saved by @hasan #laravel #php #filtering #search #eloquent

public function index(Travel $travel, ToursListRequest $request)
    {
        $tours = $travel->tours()
            ->when($request->priceFrom, function ($query) use ($request) {
                $query->where('price', '>=', $request->priceFrom * 100);
            })
            ->when($request->priceTo, function ($query) use ($request) {
                $query->where('price', '<=', $request->priceTo * 100);
            })
            ->when($request->dateFrom, function ($query) use ($request) {
                $query->where('starting_date', '>=', $request->dateFrom);
            })
            ->when($request->dateTo, function ($query) use ($request) {
                $query->where('starting_date', '<=', $request->dateTo);
            })
            ->when($request->sortBy, function ($query) use ($request) {
                if (! in_array($request->sortBy, ['price'])
                    || (! in_array($request->sortOrder, ['asc', 'desc']))) {
                    return;
                }

                $query->orderBy($request->sortBy, $request->sortOrder);
            })
            ->orderBy('starting_date')
            ->paginate();

        return TourResource::collection($tours);
    }
content_copyCOPY

GET api/v1/travels/{travel_slug}/tours - endpoint with parameters: --data "{ \"priceFrom\": \"\\\"123.45\\\"\", \"priceTo\": \"\\\"234.56\\\"\", \"dateFrom\": \"\\\"2023-06-01\\\"\", \"dateTo\": \"\\\"2023-07-01\\\"\", \"sortBy\": \"\\\"price\\\"\", \"sortOrder\": \"\\\"asc\\\" or \\\"desc\\\"\" }"
https://github.com/LaravelDaily/Laravel-Travel-API-Course/blob/main/app/Http/Controllers/Api/V1/TourController.php