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.
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!
Hi! I'm Mike Dalisay, the co-founder of codeofaninja.com, a site that helps you build web applications with PHP and JavaScript. Need support? Comment below or contact [email protected]
I'm also passionate about technology and enjoy sharing my experience and learnings online. Connect with me on LinkedIn, Twitter, Facebook, and Instagram.