Reputation: 17
I plan to upgrade my CakePHP v2 to v3 website. So I start to learn by looking at the Blog tutorial & it work fine.
Next, I start to customize base on my CakePHP v2 site.
The first thing I would like to do is using slug in URL instead of id. I add slug column in database.
But I always get an error when I click the url with the slug. The error is
Notice (8): Undefined property: Cake\ORM\Query::$created [APP/Template/Articles/view.ctp, line 3]
Help on this is greatly appreciated.
This is my routes
$routes->connect('/', ['controller' => 'Articles', 'action' => 'index']);
$routes->connect('/articles/:slug', ['controller' => 'Articles', 'action' => 'view'], ['pass' => ['slug']]);
This is my controller
public function index()
{
$this->set('articles', $this->Articles->find('all'));
}
public function view($slug = null)
{
$article = $this->Articles->findBySlug($slug);
$this->set(compact('article'));
}
This is my index.ctp
<h1>Blog articles</h1>
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Created</th>
<th>Slug</th>
</tr>
<?php foreach ($articles as $article): ?>
<tr>
<td><?= $article->id ?></td>
<td>
<?= $this->Html->link($article->title, ['action' => 'view', $article->slug]) ?>
</td>
<td>
<?= $article->created ?>
</td>
<td>
<?= $article->slug ?>
</td>
</tr>
<?php endforeach; ?>
Upvotes: 0
Views: 2003
Reputation: 6767
find()
method returns a query object. Since you want the single entity that matches that slug, call first()
on the query object:
$article = $this->Articles->findBySlug($slug)->first();
Upvotes: 1