Reputation: 895
So I have this Model, which am going to name Clients Clients has
I chose this way to get the phone numbers grouped by cities
return Clients::select('name','phone','city')->selectSub('lpad(phone,1,'0'))->where('active',1)->groupBy('city')->paginate(10);
I want to slice the collection to a sub collection from a certain client, in other terms, if I have the following output :
How can I proceed to slice this collection so as to get the 2 last items (4 last items, 6 items ... in other terms from an entry I select) I know Laravel has a slice method for collections, but how to do that dynamically ? Thank you.
Upvotes: 1
Views: 16303
Reputation: 3261
$records = Clients::select('name','phone','city')->selectSub('lpad(phone,1,'0'))->where('active',1)->groupBy('city')->paginate(10);
Assuming $name = "Jane"
$value = collect($records)->filter(function($value) use ($name) {
return $value->name === $name;
})->keys()->first();
Here $value will hold the index of Jane.
Now you can achieve the slicing by
$records = collect($records)->slice($value, 2)->all();
But there is one side effect, if the name isn't found, you will get $value as null. Check whether $value is null or not before processing slicing.
Upvotes: 5