8: Delete and conclusion

Posted under » CakePHP on 12 Dec 2018

Next, let’s make a way for users to delete articles. Start with a delete() action in the ArticlesController.

// src/Controller/ArticlesController.php
public function delete($slug)
   {
   $this->request->allowMethod(['post', 'delete']);
   $article = $this->Articles->findBySlug($slug)->firstOrFail();
   if ($this->Articles->delete($article)) {
   $this->Flash->success(__('The {0} article has been deleted.', $article->title));
   return $this->redirect(['action' => 'index']);
    }
   }

This logic deletes the article specified by $slug, and uses $this->Flash->success() to show the user a confirmation message after redirecting them to "/articles".

If the user attempts to delete an article using a GET request, allowMethod() will throw an exception. Uncaught exceptions are captured by CakePHP’s exception handler, and a nice error page is displayed. There are many built-in Exceptions that can be used to indicate the various HTTP errors your application might need to generate.Allowing content to be deleted using GET requests is very dangerous, as web crawlers could accidentally delete all your content. That is why we used allowMethod() in our controller.

Because we’re only executing logic and redirecting to another action, this is the only action without a template. You might want to update your index template with links that allow users to delete articles:

<!-- File: src/Template/Articles/index.ctp (delete links added) -->
<h1>Articles
<p><?= $this->Html->link("Add Article", ['action' => 'add']) ?>
<table>
<tr>
<th>Title
<th>Created
<th>Action
</tr>
<!-- Here's where we iterate through our $articles query object, printing out article info -->
<¿php foreach ($articles as $article): ?>
<tr>
<td>
<?= $this->Html->link($article->title, ['action' => 'view', $article->slug]) ?>
</td>
<td>
<?= $article->created->format(DATE_RFC850) ?>
</td>
<td>
<?= $this->Html->link('Edit', ['action' => 'edit', $article->slug]) ?> |
<?= $this->Form->postLink('Delete',['action' => 'delete', $article->slug],['confirm' => 'Are you sure?']) ?>
</td>
</tr>
<¿php endforeach; ?>
</table>

Conclusion

As of 13 Dec. 18, I can see the potential time saving features. I just hope I don't lose what I've learnt developing with just plain php in achieving the same tasks. It looks and feel like Symfony but you can achieve more with lesser code. But then again, you will lose flexibility along the way.

web security linux ubuntu GIT svn Raspberry apache mysql php drupal cake symfony javascript Ajax css