Simple CRUD Operation in CakePHP 3

Abhigyan Singh 01st Oct 2020

CakePHP is a powerful and robust PHP framework that uses MVC design patterns. Before you can start your first CakePHPcode, you should understand what MVC is. MVC stand for Model View Control. It means that your application is divided into three parts models, views, and controllers.

This tutorial will explain about CRUD Operation in CakePHP. Here we will show mysql Insert, Select, Update, Delete operation in cakePHP Framework.

CakePHP is a powerful and robust PHP framework that uses MVC design patterns. Before you can start your first CakePHPcode, you should understand what MVC is.

MVC stand for Model View Control. It means that your application is divided into three parts models, views, and controllers. Models are the part that responsible for connecting to database, get and save data from the database. Models represent database table in objects that you can use in the controller of your app.

Controllers have the logic of your application .It can get any data saved in your database from the Model objects then modify it or do any functionality then register this manipulated data to objects or variables to be used in views.

In the opposite direction, Controller receives data sent by views and manipulate it then call models objects to save it. Views represent the user interface of your application.

Each view is a template file that views the objects and variables registered by a controller, implements HTML ,CSS or other presentation languages and has the forms that gather data from users and send it to the controller.

Views shouldn’t have any complex logic code, only the simple code that loops through represented data like foreach, if and while constructs.

In this tutorial you will learn how your app can create , read, update and delete (CRUD) data using CakePHP MVC code .
You can download latest versions of CakePHP from this link https://github.com/cakephp/cakephp/releases. I use this version https://github.com/cakephp/cakephp/releases?after=3.2.11.

You can configure your database options from config/app.php in line 220
Change the value of these elements (host – username – database – password) to your database data.

'Datasources' => [
'default' => [
'className' => 'Cake\Database\Connection',
'driver' => 'Cake\Database\Driver\Mysql',
'persistent' => false,
'host' => 'localhost',
/**
* CakePHP will use the default DB port based on the driver selected
* MySQL on MAMP uses port 8889, MAMP users will want to uncomment
* the following line and set the port accordingly
*/
//'port' => 'non_standard_port_number',
'username' => 'root',
'password' => '',
'database' => 'discussdesk',
'encoding' => 'utf8',
'timezone' => 'UTC',
'flags' => [],
'cacheMetadata' => true,
'log' => false,

Step 1:

Create topics table in your database .This table will be used in making CRUD By inserting, selecting, updating and deleting its records.

CREATE TABLE `topics` (
  `id` int(14) UNSIGNED NOT NULL,
  `title` varchar(150) NOT NULL,
  `content` text NOT NULL,
  `tags` varchar(255) NOT NULL,
  `author` varchar(100) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Then insert two new records.

INSERT INTO `topics` (`id`, `title`, `content`, `tags`, `author`, `created`, `modified`) VALUES
(1, 'My topic title', 'the content of my topic her .the content of my topic her .the content of my topic her .the content of my topic her .the content of my topic her .', 'topic,new', 'auther name her', '2016-08-15 00:00:00', '0000-00-00 00:00:00'),
(2, 'first bite in cakephp', 'Learn how to make crud in cakephp .', 'cakephp,first', 'cakephpdevelpoer', '2016-08-15 00:00:00', '0000-00-00 00:00:00');

Step2: Create topics model

In /Model/Table/ path we will create the model class file .It will be named TopicsTable.php .This is the class who will contact with the database.

<?php

namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Validation\Validator;

classTopicsTable extends Table
{

}
?>
Step3 : Create topics controller

In /Controller/ path we will create the Controller class file .It will be named TopicsController.php .This class is a link between the topics model and the topics views.

<?php

namespace App\Controller;

use App\Controller\AppController;

classTopicsController extends AppController
{

public function initialize()
{
parent::initialize();
$this->loadComponent('Flash'); // Include the FlashComponent
}

?>

In the TopicsControllerclass, We will add the basic action by adding index() function. It will get all records from the model and register it to be viewed in view.

<?php

namespace App\Controller;

use App\Controller\AppController;

classTopicsController extends AppController
{

public function initialize()
{
parent::initialize();
$this->loadComponent('Flash'); // Include the FlashComponent

public function index()
{
$this->set('topics', $this->Topics->find('all'));
}
}
?>

Step4: Create first view file/template

In / Template/    path we will create a new folder that contains the name of our view / Template/Topics   inside this directory we will put view templates that display our data in the application's UI. The first view file index.ctp view all records sent by index() action in TopicsController class.

<!-- $this->Html is the form helper object that contain code snippets for html elements like forms, links etc
link() method generate html link
-->
<h1>Blog topics</h1>
<p><?= $this->Html->link('Add Topic', ['action' => 'add']) ?></p>
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Created</th>
<th>Actions</th>
</tr>

<!-- Here's where we loop through our $topics query object, printing out topic info -->

<?php foreach ($topics as $topic): ?>
<tr>
<td><?= $topic->id ?></td>
<td>
<?= $this->Html->link($topic->title, ['action' => 'view', $topic->id]) ?>
</td>
<td>
<?= $topic->created->format(DATE_RFC850) ?>
</td>
<td>
<?= $this->Form->postLink(
'Delete',
['action' => 'delete', $topic->id],
['confirm' => 'Are you sure?'])
?>
<?= $this->Html->link('Edit', ['action' => 'edit', $topic->id]) ?>
</td>
</tr>
<?php end foreach; ?>

</table>

Notice : view template for specific action has the same name of the controller ended with (.ctp) extension.

Now in your localhost, you can view all records as a user using this URL localhost/yoursite/topics or localhost/yoursite/topics/index.

Step5: Complete other CRUD actions and views

In TopicsController class, we will add four functions:
view($id) function view all data of specified topic by its id . add() function to insert new topics, edit ($id) function helps you update topics using its id and delete($id) function to delete any functions using its id  .Here is your complete controller.

<?php

namespace App\Controller;

use App\Controller\AppController;

classTopicsController extends AppController
{

public function initialize()
{
parent::initialize();

$this->loadComponent('Flash'); // Include the FlashComponent
}

public function index()
{
$this->set('topics', $this->Topics->find('all'));
}

public function view($id)
{
$topic = $this->Topics->get($id);
$this->set(compact('topic'));
}

public function add()
{
$topic = $this->Topics->newEntity();
if ($this->request->is('post')) {
$topic = $this->Topics->patchEntity($topic, $this->request->data);
if ($this->Topics->save($topic)) {
$this->Flash->success(__('Your topic has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to add your topic.'));
}
$this->set('topic', $topic);
}
public function edit($id = null)
{
$topic = $this->Topics->get($id);
if ($this->request->is(['post', 'put'])) {
$this->Topics->patchEntity($topic, $this->request->data);
if ($this->Topics->save($topic)) {
$this->Flash->success(__('Your topic has been updated.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to update your topic.'));
}

$this->set('topic', $topic);
}
public function delete($id)
{
$this->request->allowMethod(['post', 'delete']);

$topic = $this->Topics->get($id);
if ($this->Topics->delete($topic)) {
$this->Flash->success(__('The topic with id: {0} has been deleted.', h($id)));
return $this->redirect(['action' => 'index']);
}
}
}
?>

We will make templates file that represents controller actions. So, we will create add.ctp, view.ctp and edit.ctp. We won't make a template file for delete action as it redirects the user to index action.

add.ctp represents an HTML form to add new topics.

<h1>Add Topic</h1>
<?php
echo $this->Form->create($topic);
echo $this->Form->input('title');
echo $this->Form->input('content', ['rows' => '3']);
echo $this->Form->input('tags');
echo $this->Form->input('author');
echo $this->Form->button(__('Save Topic'));
echo $this->Form->end();
?>

view.ctp used to view topic data from $topic object inside html elements.

<h1><?= h($topic->title) ?></h1>
<p><?= h($topic->content) ?></p>

<p>Tags :<?= h($topic->tags) ?></p>
By <h3><?= h($topic->author) ?></h3>
<p><small>Created: <?php echo $topic->created->format(DATE_RFC850) ?></small></p>

edit.ctp views an HTML form contains the data of specific topic so you can make changes and submit the form to update this topic .

<!-- File: src/Template/Topics/edit.ctp -->

<h1>Edit Topic</h1>
<?php
echo $this->Form->create($topic);
echo $this->Form->input('title');
echo $this->Form->input('content', ['rows' => '3']);
echo $this->Form->input('tags');
echo $this->Form->input('author');
echo $this->Form->button(__('Save Topic'));
echo $this->Form->end();
?>

At the end of this article, you have had your first bite in CakePHP. You have understood the MVC technique in general.

If you have any query regarding CakePHP, feel free to write in comment section

Authored By Abhigyan Singh

He is a continuous blogger and has blogged on different topic. He loves to surf Internet and always trying to get new Idea about new Technology and Innovations and sharing these great information to all the technology lovers.

Also on DiscussDesk