Summer Sale! All accounts are 50% off this week.

IgorArnaut's avatar

Empty query parameters are not appended with withQueryParams

I have submitted a form whose fields can be empty and the resulting query string is pretraga?grad=&broj_soba=&m2_od=&m2_do=&cena_od=&cena_do=.

Filter template (realestate\resources\views\components\listings\list\form.blade.php):

search passes filtered listings to the view (realestate\app\Http\Controllers\ListingController.php):

public function search(Request $request)
{
    $order = $request->query("redosled", "");
    $listings = $this->listingServ->filter($request->query(), $order);
    // $listings = $this->appends($listings, $request->query());

    $data = $this->indexData($listings);
    return view("listings.listing_list", $data);
}

filter returns filtered listings page (realestate\app\Services\ListingService.php):

public function filter(array $data, string $order)
{
    // 1 Parametrized queries
    $query = Listing::query();
    $query = ListingFilters::filter($query, $data);
    return $this->orderPaginate($query, $order);
}

Functions that filters the listings (realestate\app\Services\ListingFilters.php):

Pagination template (realestate\resources\views\components\pagination.blade.php):

When I hover over pagination links after searching/filtering, their URLs do not include other query parameters.

What dd($request->query()) prints:

array:6 [▼ // app\Http\Controllers\ListingController.php:113
  "grad" => null
  "broj_soba" => null
  "m2_od" => null
  "m2_do" => null
  "cena_od" => null
  "cena_do" => null
]
0 likes
2 replies
Shivamyadav's avatar

Try with this

Give it a try with this update d code for your search method to have the listings with the query strings.

public function search(Request $request)
{
    $order = $request->query("redosled", "");
    $listings = $this->listingServ->filter($request->query(), $order);
     // Add this line to attach all request parameters to the pagination links
    $listings->withQueryString(); 

    $data = $this->indexData($listings);
    return view("listings.listing_list", $data);
}
IgorArnaut's avatar

This does not fix the issue where empty/null query parameters are not appended in pagination query strings.

Shivamyadav's avatar

Try this then manually setting up the empty query string to append

public function search(Request $request)
{
    $order = $request->query("redosled", "");
    $listings = $this->listingServ->filter($request->query(), $order);

    // Converting explicit nulls into empty strings
    $allQueryParams = array_map(function ($value) {
        return is_null($value) ? '' : $value;
    }, $request->query());

    $listings->appends($allQueryParams);

    $data = $this->indexData($listings);
    return view("listings.listing_list", $data);
}

Please or to participate in this conversation.