Skip to content

Commit

Permalink
add flexibility to Post setUrl method (#506)
Browse files Browse the repository at this point in the history
* 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]>
  • Loading branch information
4 people authored Jul 11, 2020
1 parent 5ccd9a6 commit 610e41a
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
5 changes: 3 additions & 2 deletions components/Posts.php
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ protected function prepareVars()
protected function listPosts()
{
$category = $this->category ? $this->category->id : null;
$categorySlug = $this->category ? $this->category->slug : null;

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

$post->categories->each(function($category) {
$category->setUrl($this->categoryPage, $this->controller);
Expand Down
13 changes: 8 additions & 5 deletions models/Post.php
Original file line number Diff line number Diff line change
Expand Up @@ -152,17 +152,20 @@ public function beforeSave()
* Sets the "url" attribute with a URL to this object.
* @param string $pageName
* @param Controller $controller
* @param array $params Override request URL parameters
*
* @return string
*/
public function setUrl($pageName, $controller)
public function setUrl($pageName, $controller, $params = [])
{
$params = [
$params = array_merge([
'id' => $this->id,
'slug' => $this->slug
];
'slug' => $this->slug,
], $params);

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

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

0 comments on commit 610e41a

Please sign in to comment.