0

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?

1
  • You can implement this or use something existing to build rest requests that translate to queries like graphql, json api and then some. Commented Apr 7, 2019 at 20:44

1 Answer 1

1

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
   * ]
   */
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.