4: creating the article detail page

Posted under » CakePHP on 11 Dec 2018

Continued from the create summary view article.

Add the view function to existing src/Controller/ArticlesController.php file

// src/Controller/ArticlesController.php
namespace App\Controller;
class ArticlesController extends AppController
 public function index()
  $articles = $this->Paginator->paginate($this->Articles->find());

public function view($slug = null)
  $article = $this->Articles->findBySlug($slug)->firstOrFail();

The findBySlug() allows us to create a basic query that finds articles by a given slug.

We then use firstOrFail() to either fetch the first record, or throw a NotFoundException.

Our action takes a $slug parameter, but where does that parameter come from? If a user requests '/articles/view/first-post', then the value ‘first-post’ is passed as $slug by CakePHP’s routing and dispatching layers.

If we reload our browser with our new action saved, we’d see another CakePHP error page telling us we’re missing a view template; let’s fix by creating the view for our new ‘view’ action and place it in 'src/Template/Articles/view.ctp'

<!-- File: src/Template/Articles/view.ctp -->
<h1><?= h($article->title) ?>
<p><?= h($article->body) ?>
<p><small>Created: <?= $article->created->format(DATE_RFC850) ?>
<p><?= $this->Html->link('Edit', ['action' => 'edit', $article->slug]) ?>

You can verify that this is working by trying the links at /articles/index or manually requesting an article by accessing URLs like /articles/view/first-post.

Next we learn how to add a new record and edit a record.

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