问题
So I have this Model, which am going to name Clients Clients has
- id int PK
- name varchar
- phone int
- city varchar
- active tinyint
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 :
- John 0123456 Paris
- Jake 0255664 Montreal
- Jane 0165656 London
- Fred 0164465 Toronto
- Joan 0556494 Barcelona
- Pete 0656897 Roma
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.
回答1:
$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.
来源:https://stackoverflow.com/questions/41664610/laravel-slice-collection-after-an-element