'How can I fetch and share posts by "ids" for different webpages in Laravel?
Having three different pages and 100 posts, how can one fetch latest posts shared on these three pages? 30 posts (ID -> 100 to 71) for page 1, 30 posts (ID -> 70 to 41) for page 2 and 40 posts (ID -> 40 to 1) for page 3. Is this possible? I have been able to achieve only the first part like this:
$page1 = Post::with('author')->latest()->take(30)->get(); // This gave me exactly 30 latest posts
Also, I would like to apply pagination but don’t know how to chain it along with what I have.
I would so much appreciate a help here. Thanks.
Solution 1:[1]
As mentioned in the comments, what you are looking for is Pagination.
https://laravel.com/docs/7.x/pagination#introduction
Typically, pagination works by taking the requested amount and displaying that number of results. If there aren't that number available it will display as many as it can.
In your scenario, it would be 30,30,30,10 rather than 30,30,40.
Again, a typical use of pagination would be to use a single page but use GET parameters in the URL to switch the content of the pages. i.e.
https://mydomain/index?page=1
https://mydomain/index?page=2
https://mydomain/index?page=3
The part of the documation which covers this is here:
https://laravel.com/docs/7.x/pagination#displaying-pagination-results
Solution 2:[2]
Finally here’s what I came up with and it worked just as I intended.
I declared query scopes in my Post model like this:
public function scopeLoadThirty($query)
{
return $query->whereBetween(‘id’, [71, 100]);
}
public function scopeLoadNextThirty($query)
{
return $query->whereBetween(‘id’, [41, 70]);
}
public function scopeLoadFinal($query)
{
return $query->whereBetween(‘id’, [1, 40]);
}
Then in my Post controller in index methods, I queried like this...
use App\Post;
public function indexOne()
{
$page1 = Post::LoadThirty()->with(‘authors’)->where(‘category’, ‘Catering’)->latest()->paginate(5);
return view(‘posts.indexOne‘, compact(‘page1’));
}
public function indexTwo()
{
$page2 = Post::LoadNextThirty()->with(‘authors’)->where(‘category’, ‘Engineering’)->latest()->paginate(5);
return view(‘posts.indexTwo’, compact(‘page2’));
}
public function indexThree()
{
$page3 = Post::LoadFinal()->with(‘authors’)->where(‘category’, ‘Tech’)->latest()->paginate(5);
return view(‘posts.indexThree’, compact(‘page3’));
}
This worked exactly as I had in mind.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Spholt |
| Solution 2 | cd4success |
