Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to use CRUD (Create, Read, Update, Delete) in Cakephp 3.0

    • 0
    • 0
    • 0
    • 0
    • 3
    • 0
    • 0
    • 0
    • 6.92k
    Comment on it

    Hello Reader's ,

    Hope your are doing good today.

    After working on CURD in cakephp 2.x+ version ,today i am going to update you with Cakephp 3.0 CURD example.

    Some directory changes made in cakephp 3.0 you can read here http://book.cakephp.org/3.0/en/intro/cakephp-folder-structure.html

    Now let's start CURD with Cakephp 3.0.

    Step 1:

    First you need to create a database & tables.

    1. CREATE DATABASE `blog`;
    2.  
    3. USE `blog`;
    4.  
    5. #Table :-articles
    6.  
    7. CREATE TABLE `articles` (
    8. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    9. `title` varchar(50) DEFAULT NULL,
    10. `body` text,
    11. `created` datetime DEFAULT NULL,
    12. `modified` datetime DEFAULT NULL,
    13. PRIMARY KEY (`id`)
    14. );

    Step 2: Configure your database.

    Location : config/app.php

    1. Datasources' => [
    2. 'default' => [
    3. 'className' => 'Cake\Database\Connection',
    4. 'driver' => 'Cake\Database\Driver\Mysql',
    5. 'persistent' => false,
    6. 'host' => 'localhost',
    7. 'username' => 'root', // your mysql user name
    8. 'password' => 'root', //your mysql password
    9. 'database' => 'blog', // databse name
    10. 'encoding' => 'utf8',
    11. 'timezone' => 'UTC',
    12. 'cacheMetadata' => true,
    13. 'quoteIdentifiers' => false,
    14. ]

    Step 3: Now create our model, view and controller for our CRUD application.

    Model: go to your project folder and create  ArticlesTable "src/Model/Table/ArticlesTable.php"

    1. // Naming conventions are very important in CakePHP. By naming our Table object ArticlesTable, CakePHP can automatically infer that this Table object will be used in the ArticlesController, and will be tied to a database table called articles.
    2.  
    3.  
    4. namespace App\Model\Table;
    5.  
    6. use Cake\ORM\Table;
    7.  
    8. class ArticlesTable extends Table
    9. {
    10. public function initialize(array $config)
    11. {
    12. $this->addBehavior('Timestamp'); //It will help to store created datetime in db
    13. }
    14. }

    Controller:

    go to your project folder and create  ArticlesController "src/Controller/ArticlesController.php"

    1. <?php
    2.  
    3. namespace App\Controller;
    4.  
    5. class ArticlesController extends AppController
    6. {
    7.     public function initialize()
    8. {
    9. parent::initialize();
    10.  
    11. $this->loadComponent('Flash'); // Include the FlashComponent
    12. }
    13.      public function index()
    14. {
    15.         $this->layout = false;
    16.         $this->set('articles', $this->Articles->find('all'));        
    17. }
    18. // View Atricles details function
    19.  
    20. public function view($id = null)
    21. {
    22. $this->layout = false;    
    23. $articles = $this->Articles->get($id);
    24. $this->set(compact('articles'));
    25. }
    26.     
    27. //Add articles
    28. public function add()
    29. {
    30.             
    31.     $this->layout = false;
    32. $article = $this->Articles->newEntity();
    33.  
    34. //Entity is a set of one record of table and their relational table, on that you can perform operation without touch of database and encapsulate property of entity (fields of table) as you want.
    35.  
    36. if ($this->request->is('post')) {
    37. $article = $this->Articles->patchEntity($article, $this->request->data);
    38. if ($this->Articles->save($article)) {
    39. $this->Flash->success(__('Your article has     been saved.'));
    40. return $this->redirect(['action' => 'index']);
    41. }
    42. $this->Flash->error(__('Unable to add your article.'));
    43. }
    44. $this->set('article', $article);
    45. }
    46. //Edit articles
    47. public function edit($id = null)
    48.     {
    49.         $this->layout = false;
    50.         $article = $this->Articles->get($id);
    51.         if ($this->request->is(['post', 'put'])) {
    52.             $this->Articles->patchEntity($article, $this->request->data);
    53.             if ($this->Articles->save($article)) {
    54.                 $this->Flash->success(__('Your article has been updated.'));
    55.                 return $this->redirect(['action' => 'index']);
    56.             }
    57.             $this->Flash->error(__('Unable to update your article.'));
    58.         }
    59.  
    60.         $this->set('article', $article);
    61.     }
    62.  
    63. //Delete articles
    64. public function delete($id)
    65.     {
    66.         $this->request->allowMethod(['post', 'delete']);
    67.  
    68.         $article = $this->Articles->get($id);
    69.         if ($this->Articles->delete($article)) {
    70.             $this->Flash->success(__('The article with id: {0} has been deleted.', h($id)));
    71.             return $this->redirect(['action' => 'index']);
    72.         }
    73.     }        
    74.     
    75.  
    76. }

    View: Contain .ctp files, which will display our view files.
    Location:  "src/Template/Articles/index.ctp"

    1. <!DOCTYPE html>
    2. <html>
    3. <head>
    4. </head>
    5. <body>
    6. <table border="1" align="center">
    7.     <tr >
    8.     <th colspan="4"><h1>Blog Articles</h1></br>
    9.     
    10.     <p><?= $this->Html->link("Add New Article", ['controller'=>'Articles','action' => 'add']) ?></p></br></br>
    11.  
    12.     <span style="color:red"><?= $this->Flash->render('flash') ?></span></br>
    13.     </th>
    14.     </tr>
    15. <tr>
    16. <th>Id</th>
    17. <th>Title</th>
    18. <th>Created</th>
    19. <th>Action</th>
    20. </tr>
    21. <!-- Here is where we iterate through our $articles query object, printing out article info -->
    22.  
    23. <?php foreach ($articles as $article): ?>
    24. <tr>
    25. <td><?= $article->id ?></td>
    26. <td>
    27. <?= $this->Html->link($article->title, ['controller' => 'Articles','action' => 'view', $article->id]) ?>
    28. </td>
    29. <td>
    30. <?= $article->created->format(DATE_RFC850) ?>
    31. </td>
    32. <td>
    33. <?= $this->Html->link('Edit', ['action' => 'edit', $article->id]) ?>
    34. <?= $this->Form->postLink(
    35. 'Delete',
    36. ['action' => 'delete', $article->id],
    37. ['confirm' => 'Are you sure?'])
    38. ?>
    39. </td>
    40. </tr>
    41. <?php endforeach; ?>
    42. </table>
    43.  
    44. </body>
    45. </html>

    add.ctp

    Location:  "src/Template/Articles/add.ctp"

    1. <h1>Add Article</h1>
    2.  
    3. <?php
    4. echo $this->Form->create($article);
    5. echo $this->Form->input('title');
    6. echo $this->Form->input('body', ['rows' => '4']);
    7. echo $this->Form->button(__('Save Article'));
    8. echo $this->Form->end();
    9. ?>
    10.  

     

    view.ctp
    Location:  "src/Template/Articles/view.ctp"

    1. <!DOCTYPE html>
    2. <html>
    3. <head>
    4.  
    5. </head>
    6. <body>
    7. <table border="1" align="center">
    8.     <tr >
    9.     <th colspan="3"><h1>Blog Articles Details</h1></th>
    10.     </tr>
    11. <tr>
    12. <th>Title</th>
    13. <th>Body</th>
    14. <th>Created</th>
    15. </tr>
    16. <tr>
    17. <td><?= h($article->title) ?></td>
    18. <td>
    19. <?= h($article->body) ?>
    20. </td>
    21. <td>
    22. <?= $article->created->format(DATE_RFC850) ?>
    23. </td>
    24. </tr>
    25. <tr>
    26. <td colspan="3" align="center"> <?= $this->Html->link('Back', ['controller' => 'Articles','action' => 'index']) ?></td>
    27. </tr>
    28. </table>
    29.  
    30. </body>
    31.  

    edit.ctp

    Location:  "src/Template/Articles/edit.ctp"

     

    1. <h1>Edit Article</h1>
    2. <?php
    3. echo $this->Form->create($article);
    4. echo $this->Form->input('title');
    5. echo $this->Form->input('body', ['rows' => '3']);
    6. echo $this->Form->button(__('Save Article'));
    7. echo $this->Form->end();
    8. ?>

     

    Please feel free to give us your feedback in comments.

 3 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: