CakePHP – View a Record

CakePHP – View a Record

To view records of database, we first need to get hold of a table using the TableRegistry class. We can fetch the instance out of registry using get() method. The get() method will take the name of the database table as argument. Now, this new instance is used to find records from database using find() method. This method will return all records from the requested table.


Make changes in the config/routes.php file as shown in the following code.


   use CakeCorePlugin;
   use CakeRoutingRouteBuilder;
   use CakeRoutingRouter;

   Router::scope('/', function (RouteBuilder $routes) {
      $routes->connect('/users', ['controller' => 'Users', 'action' => 'index']);

Create a UsersController.php file at src/Controller/UsersController.php. Copy the following code in the controller file.


   namespace AppController;
   use AppControllerAppController;
   use CakeORMTableRegistry;
   use CakeDatasourceConnectionManager;

   class UsersController extends AppController{
      public function index(){
         $users = TableRegistry::get('users');
         $query = $users->find();

Create a directory Users at src/Template, ignore if already created, and under that directory create a View file called index.ctp. Copy the following code in that file.


<a href = "add">Add User</a>

      foreach ($results as $row):
         echo "<tr><td>".$row->id."</td>";
         echo "<td>".$row->username."</td>";
         echo "<td>".$row->password."</td>";
         echo "<td><a href = '".$this->Url->build
         (["controller" => "Users","action"=>"edit",$row->id])."'>Edit</a></td>";
         echo "<td><a href = '".$this->Url->build
         (["controller" => "Users","action"=> "delete",$row->id])."'>Delete</a></td></tr>";

Execute the above example by visiting the following URL.



Upon execution, the above URL will give you the following output.

Was this article helpful?

Related Articles

Leave A Comment?

You must be logged in to post a comment.