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!


Comments

72 responses to “Creating a CakePHP CRUD Example – Source Code Download and Tutorial”

  1. The provided coding was excellent.. Thanks for sharing!Forms

  2. 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. True, but it’s just meant to be an example, not production-ready code.

    2. Yep, just feel like it needs to be said, as so many developers follow that pattern without thinking what it does, and it then appears on many websites:

      http://www.infoq.com/news/2012/03/GitHub-Compromised

    3. @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.

  3. 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.

  4. Thanks for sharing this post, help me a lot. I used this to make my crud in my language (pt-br), and works fine with few fixes.

  5. 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..

  6. As a New learner i totally love the stuff provided above !

    Forms

  7. Bob Snot Avatar
    Bob Snot

    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. 😀

    2. Nagarjun bn Avatar
      Nagarjun bn

      Even i am having same problem.. Did u get a solution for this problem

      1. Hello @nagarjunbn would you give us your test URL? Please make sure you have named your PostsController class and file correctly.

    3. really dude Avatar
      really dude

      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?

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

  9. doesn’t it generate the code automatically like Yii? O_o

    1. Hi @972ae09ac1097037019dce3596355437, thanks for visiting! CakePHP can generate these codes automatically using the bake http://book.cakephp.org/2.0/en/console-and-shells/code-generation-with-bake.html

  10. Actually good tutorial for biginners

    1. ninjazhai Avatar
      ninjazhai

      Hi @Manuja, thanks for letting us know that this tutorial is good for beginners!

  11. Shahab Khan Avatar
    Shahab Khan

    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

    1. ninjazhai Avatar
      ninjazhai

      Hey @disqus_dQIRkQew5L , yes they are possible, you can actually take a look at my post here about CakePHP pagination http://www.codeofaninja.com/2013/07/pagination-in-cakephp.html

  12. Shahab Khan Avatar
    Shahab Khan

    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. ninjazhai Avatar
      ninjazhai

      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!

  13. Jesni Johnson Avatar
    Jesni Johnson

    Thanks a lot! Your post really helped me.

    1. ninjazhai Avatar
      ninjazhai

      You’re welcome @Jesni Johnson! I’m glad our post really helped you!

  14. thanks a lot!

  15. Nilanjan Avatar
    Nilanjan

    very good example..I need also a login/logout example

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

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

  16. Adnan Sami Avatar
    Adnan Sami

    HI Ninja i need login and logout example with sessions . And very very thanks for this example. If you have the example just send me at this following email address [email protected].

    1. ninjazhai Avatar
      ninjazhai

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

  17. pragis pragis Avatar
    pragis pragis

    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. Hello @pragispragis, what CakePHP version are you using?

      1. pragis pragis Avatar
        pragis pragis

        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. pragis pragis Avatar
        pragis pragis

        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. pragis pragis Avatar
        pragis pragis

        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. pragis pragis Avatar
        pragis pragis

        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. pragis pragis Avatar
        pragis pragis

        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.

        1. JHON CARL IGNORO (jaYCee) Avatar
          JHON CARL IGNORO (jaYCee)

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

          1. Hi @jhoncarlignorojaycee , which CakePHP version are you using?

          2. JHON CARL IGNORO (jaYCee) Avatar
            JHON CARL IGNORO (jaYCee)

            I’m using the latest one. Version 7.1.2

          3. Hi @jh@jhoncarlignorojaycee , I think the latest version of CakePHP is 3.x. Our tutorial above was based on CakePHP 2.x. We will update this tutorial soon.

          4. JHON CARL IGNORO (jaYCee) Avatar
            JHON CARL IGNORO (jaYCee)

            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]

          5. I understand. I highly recommend following the official CakePHP tutorial. See it here: https://book.cakephp.org/3.0/en/tutorials-and-examples/blog/blog.html

  18. pragis pragis Avatar
    pragis pragis

    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.

  19. pranav Avatar
    pranav

    thanx a lot it worked perfectly…

    1. You are welcome @disqus_P5mJ3ZB0Wi, I’m glad it worked perfectly for you!

  20. Nagarjun Avatar
    Nagarjun

    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. @Nagarjun what CakePHP version are you using? It should work fine with CakePHP 2.x

      1. Nagarjun Avatar
        Nagarjun

        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

        1. I’m glad you fixed the error @Nagarjun! Would you tell us more about how you fixed it?

      2. Fatima Zahra Zacraoui Avatar
        Fatima Zahra Zacraoui

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

      3. Fatima Zahra Zacraoui Avatar
        Fatima Zahra Zacraoui

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

  21. Meer-Sahab Avatar
    Meer-Sahab

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

    1. Hello @Meer-Sahab, would you specify that error message?

  22. help

  23. i need help …you can send the tutorial?? thanks…[email protected]

    1. Hello @Andres, you can always download the source code on the link provided above..

  24. Angela Patricia Mayor Ortiz Avatar
    Angela Patricia Mayor Ortiz

    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

  25. Randheer kumar Avatar
    Randheer kumar

    how to access multiple table in a database

    1. Hello @Randheer, we’ll work on that feature soon. Thanks for the suggestion!

  26. Arun kumar singh Avatar
    Arun kumar singh

    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….

    1. Hi @Arun, what exactly is the error? Any error message?

  27. Rameshwar Shashtri Avatar
    Rameshwar Shashtri

    You are suggest to me.

    1. Hi @rameshwarshashtri , would you tell us what exactly is the error message? Please note that we are using CakePHP 2.x here.

  28. rahul rai Avatar
    rahul rai

    hi mike where are your database this folder not include database file

    1. Hi @disqus_3xcpPGnzSB , please run our SQL query above on your PhpMyAdmin.

  29. Hi @disqus_VE46ryLgEc, unfortunately we don’t have an updated tutorial for that. I suggest learning in udemy here: https://www.udemy.com/courses/search/?q=cakephp&src=sac&kw=cakephp

  30. Hi @shivutj, you can always learn CSS for that. Learn from sites like https://www.csstutorial.net/

  31. Hi @shivutj, your can add it inside the head tag. I suggest you learn from our tutorial here: https://www.codeofaninja.com/2014/05/bootstrap-tutorial-beginners-step-step.html

  32. Hi @michael_dirk, thanks for your comment! Unfortunately this tutorial will work only with CakePHP 2.x.

  33. Hi @michael_dirk, I was working on a software project and was unable to review the comments on this blog. Sorry about that!

  34. 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.

Leave a Reply

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