Creating a CakePHP CRUD Example – Source Code Download and Tutorial

Hey guys, today I just want to update my CakePHP CRUD example or tutorial from 1.3.x to 2.x. Please note that this post can really help you get started with CakePHP database operations but is just meant to be an example, not production-ready code, use and customize it according to your needs.

Using CakePHP 2.x can give us lots of benefits such as improved support for PostgreSql, SQLite and SqlServer, HTML 5 form inputs support in form helper, a sexier default look taking advantage of new CSS 3 features, a lot faster, almost everything is now lazy-loaded, and even on debug mode you will feel your applications flying, more here, here and here.

cakephp crud example

MySQL Database Table Used

Here we are using a “users” table with such fields.

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `email` varchar(32) NOT NULL,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=58 ;

The default layout was used in this tutorial. It was found in app/View/Layouts/default.ctp

CakePHP CRUD Example (CakePHP Version 2.x)

Below are the actual CakePHP create, read, update and delete (CRUD) operations. This an be your quick reference in case you need it or want someone to learn about it. Enjoy!

Create a Record in CakePHP

Answers the question, how to create a record in CakePHP?

Controller: app/Controller/UsersController.php

public function add(){
 
    //check if it is a post request
    //this way, we won't have to do if(!empty($this->request->data))
    if ($this->request->is('post')){
        //save new user
        if ($this->User->save($this->request->data)){
         
            //set flash to user screen
            $this->Session->setFlash('User was added.');
            //redirect to user list
            $this->redirect(array('action' => 'index'));
             
        }else{
            //if save failed
            $this->Session->setFlash('Unable to add user. Please, try again.');
             
        }
    }
}

View: app/View/Users/add.ctp

<h2>Add New User</h2>
 
<!-- link to add new users page -->
<div class='upper-right-opt'>
    <?php echo $this->Html->link( 'List Users', array( 'action' => 'index' ) ); ?>
</div>
 
<?php 
//this is our add form, name the fields same as database column names
echo $this->Form->create('User');
 
    echo $this->Form->input('firstname');
    echo $this->Form->input('lastname');
    echo $this->Form->input('email');
    echo $this->Form->input('username');
    echo $this->Form->input('password', array('type'=>'password'));
     
echo $this->Form->end('Submit');
?>

Read Records in CakePHP

This time it answers, how to read records in CakePHP and display it in a table?

Controller: app/Controller/UsersController.php

public function index() {
    //to retrieve all users, need just one line
    $this->set('users', $this->User->find('all'));
}

View: app/View/Users/index.ctp

<h2>Users</h2>
 
<!-- link to add new users page -->
<div class='upper-right-opt'>
    <?php echo $this->Html->link( '+ New User', array( 'action' => 'add' ) ); ?>
</div>
 
<table style='padding:5px;'>
    <!-- table heading -->
    <tr style='background-color:#fff;'>
        <th>ID</th>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Username</th>
        <th>Email</th>
        <th>Actions</th>
    </tr>
     
<?php
 
     
    //loop to show all retrieved records
    foreach( $users as $user ){
     
        echo "<tr>";
            echo "<td>{$user['User']['id']}</td>";
            echo "<td>{$user['User']['firstname']}</td>";
            echo "<td>{$user['User']['lastname']}</td>";
            echo "<td>{$user['User']['username']}</td>";
            echo "<td>{$user['User']['email']}</td>";
             
            //here are the links to edit and delete actions
            echo "<td class='actions'>";
                echo $this->Html->link( 'Edit', array('action' => 'edit', $user['User']['id']) );
                 
                //in cakephp 2.0, we won't use get request for deleting records
                //we use post request (for security purposes)
                echo $this->Form->postLink( 'Delete', array(
                        'action' => 'delete', 
                        $user['User']['id']), array(
                            'confirm'=>'Are you sure you want to delete that user?' ) );
            echo "</td>";
        echo "</tr>";
    }
?>
     
</table>

Update a Record in CakePHP

Answers the question, how to edit or update a record in CakePHP?

Controller: app/Controller/UsersController.php

public function edit() {
    //get the id of the user to be edited
    $id = $this->request->params['pass'][0];
     
    //set the user id
    $this->User->id = $id;
     
    //check if a user with this id really exists
    if( $this->User->exists() ){
     
        if( $this->request->is( 'post' ) || $this->request->is( 'put' ) ){
            //save user
            if( $this->User->save( $this->request->data ) ){
             
                //set to user's screen
                $this->Session->setFlash('User was edited.');
                 
                //redirect to user's list
                $this->redirect(array('action' => 'index'));
                 
            }else{
                $this->Session->setFlash('Unable to edit user. Please, try again.');
            }
             
        }else{
         
            //we will read the user data
            //so it will fill up our html form automatically
            $this->request->data = $this->User->read();
        }
         
    }else{
        //if not found, we will tell the user that user does not exist
        $this->Session->setFlash('The user you are trying to edit does not exist.');
        $this->redirect(array('action' => 'index'));
             
        //or, since it we are using php5, we can throw an exception
        //it looks like this
        //throw new NotFoundException('The user you are trying to edit does not exist.');
    }
     
 
}

View: app/View/Users/edit.ctp

<h2>Edit User</h2>
 
<!-- link to add new users page -->
<div class='upper-right-opt'>
    <?php echo $this->Html->link( 'List Users', array( 'action' => 'index' ) ); ?>
</div>
 
<?php 
//this is our edit form, name the fields same as database column names
echo $this->Form->create('User');
 
    echo $this->Form->input('firstname');
    echo $this->Form->input('lastname');
    echo $this->Form->input('email');
    echo $this->Form->input('username');
    echo $this->Form->input('password', array('type'=>'password'));
     
echo $this->Form->end('Submit');
?>

Delete a Record in CakePHP

This answers the questions, how to delete a record in CakePHP?

We won’t have view for delete because this is triggered only when the user clicked the delete option on the index page and clicked ok on the pop up.

Controller: app/Controller/UsersController.php

public function delete() {
    $id = $this->request->params['pass'][0];
     
    //the request must be a post request 
    //that's why we use postLink method on our view for deleting user
    if( $this->request->is('get') ){
     
        $this->Session->setFlash('Delete method is not allowed.');
        $this->redirect(array('action' => 'index'));
         
        //since we are using php5, we can also throw an exception like:
        //throw new MethodNotAllowedException();
    }else{
     
        if( !$id ) {
            $this->Session->setFlash('Invalid id for user');
            $this->redirect(array('action'=>'index'));
             
        }else{
            //delete user
            if( $this->User->delete( $id ) ){
                //set to screen
                $this->Session->setFlash('User was deleted.');
                //redirect to users's list
                $this->redirect(array('action'=>'index'));
                 
            }else{  
                //if unable to delete
                $this->Session->setFlash('Unable to delete user.');
                $this->redirect(array('action' => 'index'));
            }
        }
    }
}

Do you have any questions or suggestions about our CakePHP CRUD example? Feel free to drop it in the comments section below! If it helps you, please like or share it to your friends, thanks!

By Mike Dalisay

I'm Mike Dalisay, a pro web developer since 2010. I love web development. Improving our tutorials and source codes makes me happy. Do you want to suggest an edit to our tutorial? Got something to ask about our source codes? You may use our comments section below or email our team at [email protected]

72 comments

  1. Hi @michael_dirk, unfortunately, I got other jobs that actually paid for me to eat. Also, CakePHP 2 and 3 looks very different to me.

    For those reasons, it is hard for me to release new updates. I believe you will find more updated tutorials on Google though. Thanks for understanding.

  2. sir please help me about cakephp code, i download ur code for add,update and delete but not running during runing time genenrate errror in such as genenrate no such file or director that means generate error in webroot/index.php . so plz help me sir….

  3. ME SALE EL SIGUIENTE ERROR:

    lA LINEA 10 ESTA ASI:$this->set(‘entidades’, $this->Entidad->findAll());

    : Error: Call to a member function findAll() on null

    File: C:servidor_webcakephp-2.7.7appControllerEntidadesController.php

    Line: 10, NO se que pasa, la tabla le he cambiado el nombre a ‘entidads’. findById tambien me fallan

  4. Hey,
    I tried to run your code…but there show some warning and fatel error could you help me to short out

  5. i have downloaded your code . But i am getting a error

    Missing Method in AppController

    Error: The action View is not defined in controller AppController

    Error: Create AppController::View() in file: appControllerAppController.php.

    <?php
    class AppController extends AppController {

    public function View() {

    }

    }

    some one help me . This is my first cakp PHP project

      1. Thank you very much for your reply. I managed to remove the error. If I have any further queries in CakePHP I will contact you

      2. Hi, thank you for this tutorial , i’m using 2.6 version of cakephp but i have the same error any help please ??

      3. Hi thank you for this tutorial, i’m working with 2.6 version of cakephp, but i have the same error Any help please ??

  6. Hi Mike Dalisay ,
    I just download your code, configure the database.
    On browser,I am getting this error(please check attachment).

    this is my first project, sorry for this basic questions. Please help.

  7. Hi,
    I am a newbie on cakePHP. I have downloaded your project code. There is no composer.json file. I have tried to update the composer by using command prompt. It says,”To initialize a project, to create a composer.json file”. How could I run this project ? Please help

      1. I just downloaded your code @Mike. This is my first project in CakePHP. How to run this project.? Could you mention by points please?

      2. after extract and database confguration, i run this project. It shows below errors:

        Warning: include(Cakebootstrap.php): failed to open stream: No such file or directory in C:xampphtdocscakephpcrud_projectwebrootindex.php on line 77

        Warning: include(): Failed opening ‘Cakebootstrap.php’ for inclusion (include_path=’C:xampphtdocscakephplib;.;C:xamppphpPEAR’) in C:xampphtdocscakephpcrud_projectwebrootindex.php on line 77

        Fatal error: CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your cake core directory and your vendors root directory. in C:xampphtdocscakephpcrud_projectwebrootindex.php on line 86

        May I set any permission or do anything ?
        This is my first project. so that i am asking very basic question. Sorry. Help me

      3. Hi Mike,
        I just download your code and extraxt and setup the database connection.
        I am getting this error on browser.
        This is my first project on CakePHP. Sorry for the basic questions. Please help.

        Warning: include(Cakebootstrap.php): failed to open stream: No such file or directory in C:xampphtdocscakephpcrud_projectwebrootindex.php on line 77

        Warning: include(): Failed opening ‘Cakebootstrap.php’ for inclusion (include_path=’C:xampphtdocscakephplib;.;C:xamppphpPEAR’) in C:xampphtdocscakephpcrud_projectwebrootindex.php on line 77

        Fatal error: CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your cake core directory and your vendors root directory. in C:xampphtdocscakephpcrud_projectwebrootindex.php on line 86

      4. Hi Mike Dalisay ,
        I just download your code, configure the database.
        On browser,I am getting this error,

        Fatal error: CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your /cake core directory and your /vendors root directory. in /srv/www/php.pragis.int/cakephp/auth/webroot/index.php on line 102

        this is my first project, sorry for this basic questions. Please help.

      5. Hi Mike Dalisay ,
        I just download your code, configure the database.
        On browser,I am getting this error(please check attachment).

        this is my first project, sorry for this basic questions. Please help.

      6. I’m getting the same error as this. How are we going to fix this?

      7. I’ve been using PHP for making web application for a long time. But with the use of CakePHP is a new thing for me. I have tried using CI which uses same framework. However, I found this challenging yet difficult to start with. So I’m sorry if this basic question should have to be asked. But I am hoping for an answer. Please, if just in case I’m offline the moment you’ll receive this, kindly reach me at my email address, I really need to make this work for self-study purposes.

        Here’s my email:
        [email protected]

    1. @disqus_gr1IKAzAcH thanks for the kind words and post suggestion, glad I could help you! I’ll post more CakePHP examples in the future!

    1. After created the CRUD in this tutorial, How can I run this?

      Always appearing the default.ctp in app/View/Layouts/default.ctp

  8. HI,

    I got pagination working in users list.

    If we have search then it will be CRUD + Pagination + Search in cakephp tutorial.

    Thanks for good work.

    -Thanks

    1. Hey @disqus_dQIRkQew5L , I’m glad I was able to help you, thanks for the post suggestion, I will work on that because I think many people will find it useful!

  9. Hi Mike,

    Thanks for tutorial and source code.

    It is possible to add pagination in users list.

    I mean could you add pagination in users list.

    This will help users to understand how pagination works.

    -Thanks

  10. HI what if I have multiple tables writing code for each and everyone would be a pain, Anything like grocery crud for php

  11. cakePHP sucks. Why? Their own blog tutorial – ambiguously written – results invariably in error messages:

    Error: PostsController could not be found.
    Error: Create the class PostsController below in file: appcontrollersPostsController.php

    If those idiots cannot write out a simple “hello world” tutorial … one wonders what else they punted on.

    PHP is an old, old friend. codeigniter is not, but at least it works out of the box and is documented by humans rather than imbeciles.

    1. I respect your opinion @6ad2789df30f0e605fefe6444514c14c , but I’ve written several business web apps using CakePHP and I must say it works really good. When I first started learning CakePHP, I agree with you, I searched for other tutorials to create a blog too (to complement their docs), but after some time, their official docs makes sense and now I enjoy building web apps with CakePHP. :D

    2. So… you dont know how to use the tool, and being a total douche is the way you use to show people that cakephp is bad?

  12. I tried this… If we want to use delete option, can we delete the record permanently by using triggered and if needed can we get back the deleted record..

  13. I switched to cakephp 2.0 from cakephp 1.2. :) I used to play with the now deprecated ajax & javascript helper.
    I love cakephp i should say.

  14. Now imagine having an “admin” field in the database, perhaps a tinyint or enum(true,false)… then someone can visit your register page, and using something like FireBug, to add [input name=”admin” value=”1″] to the source code (note that is supposed to be HTML, but your comment system is blocking HTML characters instead of escaping them)… they have now created themselves an admin account because your not filtering the fields they are allowed to set in your controller.

    1. @Unknown # 2: You’re correct, it’s just meant to be an example, not production-ready code.

      And good point from @Unknown # 1, I think it needs to be said. Thanks for citing an example with an admin field even though that does not exist in this example.

      Thanks for your useful responses guys.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to top