Skip to content

Commit df66b38

Browse files
author
Luke Towers
authored
Fix 404 handling for not found posts. (#512)
Follow up to #438. Refs: https://octobercms.com/forum/post/error-when-trying-to-navigate-away-from-blog-page
1 parent 610e41a commit df66b38

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed

components/Post.php

+14-13
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
use Cms\Classes\Page;
66
use Cms\Classes\ComponentBase;
77
use RainLab\Blog\Models\Post as BlogPost;
8-
use Illuminate\Database\Eloquent\ModelNotFoundException;
98

109
class Post extends ComponentBase
1110
{
@@ -71,6 +70,10 @@ public function onRun()
7170
{
7271
$this->categoryPage = $this->page['categoryPage'] = $this->property('categoryPage');
7372
$this->post = $this->page['post'] = $this->loadPost();
73+
if (!$this->post) {
74+
$this->setStatusCode(404);
75+
return $this->controller->run('404');
76+
}
7477
}
7578

7679
public function onRender()
@@ -85,26 +88,24 @@ protected function loadPost()
8588
$slug = $this->property('slug');
8689

8790
$post = new BlogPost;
91+
$query = $post->query();
8892

89-
$post = $post->isClassExtendedWith('RainLab.Translate.Behaviors.TranslatableModel')
90-
? $post->transWhere('slug', $slug)
91-
: $post->where('slug', $slug);
92-
93-
if (!$this->checkEditor()) {
94-
$post = $post->isPublished();
93+
if ($post->isClassExtendedWith('RainLab.Translate.Behaviors.TranslatableModel')) {
94+
$query->transWhere('slug', $slug);
95+
} else {
96+
$query->where('slug', $slug);
9597
}
9698

97-
try {
98-
$post = $post->firstOrFail();
99-
} catch (ModelNotFoundException $ex) {
100-
$this->setStatusCode(404);
101-
return $this->controller->run('404');
99+
if (!$this->checkEditor()) {
100+
$query->isPublished();
102101
}
102+
103+
$post = $query->first();
103104

104105
/*
105106
* Add a "url" helper attribute for linking to each category
106107
*/
107-
if ($post && $post->categories->count()) {
108+
if ($post && $post->exists && $post->categories->count()) {
108109
$post->categories->each(function($category) {
109110
$category->setUrl($this->categoryPage, $this->controller);
110111
});

0 commit comments

Comments
 (0)