I am working on a blogging application in Laravel 8.
I run into a problem while trying to add a Next article and Previous article on the single article view.
In the ArticlesController controller I have this method to display a single article:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\ArticleCategory;
use App\Models\Article;
use App\Models\Comment;
class ArticlesController extends FrontendController {
// More code
public function show($slug) {
// Single article
$article = Article::firstWhere('slug', $slug);
$old_article = Article::firstWhere('id', '<', $article->id);
$new_article = Article::firstWhere('id', '>', $article->id);
$comments = Comment::where('article_id', $article->id)->orderBy('id', 'desc')->get();
return view('themes/' . $this->theme_directory . '/templates/single',
array_merge($this->data, [
'categories' => $this->article_categories,
'article' => $article,
'old_article' => $old_article,
'new_article' => $new_article,
'comments' => $comments,
'tagline' => $article->title,
])
);
}
}
In the Blade view:
@if($old_article)
<div >
<a href="{{ url('/show/' . $old_article->slug) }}">
<span>Older</span>
{{ $old_article->title }} {{ $old_article->id }}
</a>
</div>
@endif
@if($new_article)
<div >
<a href="{{ url('/show/' . $new_article->slug) }}">
<span>Newer</span>
{{ $new_article->title }} {{ $new_article->id }}
</a>
</div>
@endif
The problem
For a reason I was unable to understand, the link to an older post does not work.
The line {{ $old_article->id }}
always returns 1
.
Questions
- What causes this bug?
- What is the easiest fix?
CodePudding user response:
If your $article
has an ID of, let's say 10
, then all Article
records with an ID of 1 - 9 are "Older". You need to order your query so it gets the closest "Old" Article
:
$article = Article::where('slug', $slug)->firstOrFail();
$oldArticle = Article::where('id', '<', $article->id)->orderBy('id', 'DESC')->first();
$newArticle = Article::where('id', '>', $article->id)->orderBy('id', 'ASC')->first();
Your "New" Article
query was fine, default order is id, ASC
, but for clarity, it doesn't hurt to make it consistent.