CI 4 Query String in Routes

Query string means key value pairs to URL which is concatenated with & symbol. For passing query string value, we don’t need to do anything with the route configuration.

Let’s add a simple route.

Open Routes.php file from /app/Config folder.

//...

$routes->get("my-route", "MyController::myRoute");

Example URLs

  • /my-route?name=sanjay&role=auth
  • /my-route?message=success&error=0

Access URL values to Controller

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class MyController extends BaseController
{
	public function myRoute()
	{
		$all_query_values = $this->request->getVar();
        // It will return an array of all values
      
      	// get query variable - name
        $name = $this->request->getVar("name");
        // get query variable - role
        $role = $this->request->getVar("role");
	}
}
  • $this->request->getVar() – It returns all query variables with values into an array format.
  • $this->request->getVar(“name”); – It will return the single query variable value i.e name

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more