Alex
Alex

Reputation: 3072

Is there a way to interpret multi-parameter query strings in Laravel?

Is there a way to interpret multiple parameters from a query string that resembles the following?

sort=key1:asc,key2:desc,key3:asc

If not, is there a better strategy for passing sort parameters using query strings?

Upvotes: 0

Views: 50

Answers (1)

rocasan
rocasan

Reputation: 44

Not tested. In a Controller:

private function parseSortFromQueryString($sortStringToParse) 
{
  $sort = [];
  if(preg_match_all('/([a-zA-Z0-9_]+)(:(asc|desc))?/', $sortStringToParse, $matches, PREG_SET_ORDER)) {
    foreach($matches as $match) {
      $sort[$match[1]] = $match[3] ?? 'asc';
    }
  }
  return $sort;
}

public function index(Request $request) 
{
  $sort = $this->parseSortFromQueryString($request->input('sort', []));
  /* With your example
   * $sort = [
   *   key1 => asc
   *   key2 => desc
   *   key3 => asc
   * ]
   */
}

Upvotes: 1

Related Questions