I’m working on a forum project using Laravel 8, and in this project, I have made a page for getting all the questions with specific tag. Here is the the method to do that:
public function tag($name) { $tag = AppModelsTag::findOrFail($name); return view('tag',[ 'single' => $tag ]); }
And then inside tag.blade.php
:
@foreach($single->questions as $one) ... @endforeach
But now I need to add pagination for this page, so if questions are more than a custom number, they can navigate to other pages.
In fact I had already added pagination to my other page which shows all the entire questions:
public function allQuestions() { $all = Question::latest()->paginate(20); return view('questions.allquestions',[ 'all' => $all ]); }
But I don’t know really how to add this feature to tag()
method.
So if you know how to add this pagination, please let me know…
I would really appreciate any idea or suggestion from you guys.
Thanks in advance.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Theres 2 choices for this:
First Choice:
public function tag($name) { $tag = AppModelsTag::findOrFail($name); $questions = $tag->question()->paginate(10); return view('tag',[ 'single' => $tag, 'questions' => $questions ]); }
Then, on your view, you can just loop through the questions.
@foreach ($questions as $question) ... fill this @endforeach {!! $questions->render() !!}
Second Choice:
public function tag($name) { $tag = AppModelsTag::findOrFail($name); $tag->setRelation('questions',$tag->questions()->paginate(10)); return view('tag',[ 'single' => $tag ]); }
Then, on your view, you can just loop through the questions.
@foreach ($single->questions as $question) ... fill this @endforeach
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0