Skip to content

Commit 610e41a

Browse files
mjauvinBen ThomsonBen ThomsonLuke Towers
authored
add flexibility to Post setUrl method (#506)
* allow passing parameters when calling setUrl; use current category to build post url * Update components/Posts.php * Fix minor code smell * Update models/Post.php * Update models/Post.php * do not make unnecessary queries * Update models/Post.php Co-authored-by: Ben Thomson <[email protected]> Co-authored-by: Ben Thomson <[email protected]> Co-authored-by: Luke Towers <[email protected]>
1 parent 5ccd9a6 commit 610e41a

File tree

2 files changed

+11
-7
lines changed

2 files changed

+11
-7
lines changed

components/Posts.php

+3-2
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,7 @@ protected function prepareVars()
195195
protected function listPosts()
196196
{
197197
$category = $this->category ? $this->category->id : null;
198+
$categorySlug = $this->category ? $this->category->slug : null;
198199

199200
/*
200201
* List all the posts, eager load their categories
@@ -219,8 +220,8 @@ protected function listPosts()
219220
/*
220221
* Add a "url" helper attribute for linking to each post and category
221222
*/
222-
$posts->each(function($post) {
223-
$post->setUrl($this->postPage, $this->controller);
223+
$posts->each(function($post) use ($categorySlug) {
224+
$post->setUrl($this->postPage, $this->controller, ['category' => $categorySlug]);
224225

225226
$post->categories->each(function($category) {
226227
$category->setUrl($this->categoryPage, $this->controller);

models/Post.php

+8-5
Original file line numberDiff line numberDiff line change
@@ -152,17 +152,20 @@ public function beforeSave()
152152
* Sets the "url" attribute with a URL to this object.
153153
* @param string $pageName
154154
* @param Controller $controller
155+
* @param array $params Override request URL parameters
155156
*
156157
* @return string
157158
*/
158-
public function setUrl($pageName, $controller)
159+
public function setUrl($pageName, $controller, $params = [])
159160
{
160-
$params = [
161+
$params = array_merge([
161162
'id' => $this->id,
162-
'slug' => $this->slug
163-
];
163+
'slug' => $this->slug,
164+
], $params);
164165

165-
$params['category'] = $this->categories->count() ? $this->categories->first()->slug : null;
166+
if (!$params['category']) {
167+
$params['category'] = $this->categories->count() ? $this->categories->first()->slug : null;
168+
}
166169

167170
// Expose published year, month and day as URL parameters.
168171
if ($this->published) {

0 commit comments

Comments
 (0)