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.
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();
You can do it with forPage() method.
Like this:
$posts = $posts->forPage($currentPage, $perPage);
Documentation
Related
How do I get the key from a collection item?
$posts= Post::all();
Example (doesn't work):
$key = $posts->where('id', $id)->getKey();
The all() will return a collection without keys. If you're talking about integer keys like 0, 1, 2 etc, use the search() method:
$key = $posts->search(function($i) use($id) {
return $i->id === $id;
});
Try $post_ids = Post::pluck('id');
That grabs just the id column from all the Post records and returns them as a collection.
If you want just a plain array, add toArray():
$post_ids = Post::pluck('id')->toArray();
Let's say I have a model collection that I'm mapping through like this:
$alreadyImported = [];
$players = Players::whereNotIn('id', $alreadyImported)
->get()
->random(25)
->pluck('id');
$groups = $players->map(function ($item, $key) use ($alreadyImported) {
array_merge($alreadyImported, $item->id);
$group = [
'username' => $item['username'],
];
return $group;
});
// $groups is a pivot table with group and players
Why does my $globalList always start at []? How can I carry the already-merged $globalList to the next map iteration?
The player IDs does not matter. It's for show. I am looking to pass the array through the map iterations.
Just use pluck() to get IDs from the collection:
$ids = $players->pluck('id');
Or, if you just need IDs:
$ids = Players::where('banned', false)->pluck('id');
If you're going to add any other data, you don't need to merge it to some array or a collection because map() will create a new collection.
Finally, you don't need to use collect() because get() will return collection.
I'm having a simple hasMany relation between order and orderItems. What I'm trying to do is fetch the count of similar order items. This is what I've done:
$orderItems = $order->orderItems();
$distinctItems = $orderItems->groupBy('item_name')->distinct('item_name')->get();
foreach($distinctItems as $i){
$i['count'] = $orderItems->where('item_name', '=', $i->item_name)->count();
}
$order['items'] = $distinctItems;
However the count is returned for only first order Item and 0 for other items. I'm not sure why this is happening. I've also checked that where() returns null for the items except the first one.
Thanks for the help.
try using the collection only, first groupBy item_name and then on each item add count and return new collection which would look something like
$orderItems = $order->orderItems()->get();
$order['items'] = $orderItems->groupBy('item_name')->map(function($item) {
$i = $item->first();
$i->count = $item->count();
return $i;
});
Try this code.
$cnt = array();
foreach($distinctItems as $i){
$cnt[$i]['count'] = $orderItems->where('item_name', '=', $i->item_name)->count();
}
print_r($cnt);
Here is my code$titles = DB::table('roles')->lists('title');
How Can I cast $titles from a Laravel 5 collection into an associative array?
Include the ID in the function, and call from the Model:
$titles = Role::lists('title', 'id')->toArray();
Or call directly as you are doing:
$titles = DB::table('roles')->lists('title', 'id');
In this case, in an select field for example, the id will be the option value.
A laravel collection has a toArray method that will return a numerically keyed array of the contents. (The indexes will be keyed exactly as they are in the collection. To reset them call values on the collection first.)
$titles = DB::table('roles')->lists('title');
$result = $titles->toArray();
For an associative array you will need to do this manually using something like this.
$titles = DB::table('roles')->lists('title', 'id');
$result = [];
foreach($titles as $title) {
// using an ID as the key and title as the value
$result[$title->id] = $title->title;
}
I have a simple collection that I want to filter. Take the following example:
// Create an array of fruits
$array = ["banana", "apple", "orange"];
// Transform the array into a Collection object
$collection = new Illuminate\Support\Collection($array);
// We don't like banana's anymore, so we're going to filter them out
$no_bananas = $collection->filter(function($element) {
if ($element != "banana") return true;
});
// Dump out our array now, and we'll see the banana's are gone
dd($no_bananas);
Works great assuming I only ever want to filter by 'banana'. What if I want to use a variable within the filter. How do I do that?
// Create an array of fruits
$array = ["banana", "apple", "orange"];
$filterby = 'apple';
// Transform the array into a Collection object
$collection = new Illuminate\Support\Collection($array);
// We don't like banana's anymore, so we're going to filter them out
$filtered = $collection->filter(function($element) {
if ($element != $filterby) return true;
});
// Dump out our array now, and we'll see the banana's are gone
dd($filtered);
The above won't work because $filterbyisn't available in the filter() function. How would I make it available?
You can 'use' this variable TH1981, like this
$filtered = $collection->filter(function($element) use ($filterby) {
return $element != $filterby;
});
and one more tip you can make a collect with this global method
$collection = collect($array);