Reputation: 159
I want to skip, some element from collection
$post_one = Post_one::all();
$post_two = Post_two::all();
$posts = collect();
if($post_one){
foreach($post_one as $post){
$posts->push($post);
}
}
if($post_two){
foreach($post_two as $post){
$posts->push($post);
}
}
//now i want to skip n=3, element form the collection of posts
$posts = $posts->sortBy('created_at')-<skip(3)->take(3);//does not work
error::Method skip does not exist.
Upvotes: 2
Views: 3846
Reputation: 2775
You can do it with forPage()
method.
Like this:
$posts = $posts->forPage($currentPage, $perPage);
Upvotes: 0
Reputation: 7334
To combine both records you can use merge method with flatten, i,e
$posts = $post_one->flatten(1)->merge($post_two)->sortBy('created_at');
Then you use filter to get the right result:
$filtered = $posts->filter(function ($post, $key) {
return $key > 2;
});
This skips the first 3 since the key starts from 0...n.
Or you can just slice the collection:
$nextthree = $posts->slice(3, 3);
This skips 3 and takes the next 3 from the collection. You can access the original collections $posts
.
At this point the index of the collection is preserved, but to reset it to start from 0...n just use values()
method i.e:
$nextthree = $posts->slice(3, 3)->values();
Upvotes: 2