Laravel slice collection after an element

笑着哭i 提交于 2019-12-13 06:11:10

问题


So I have this Model, which am going to name Clients Clients has

  1. id int PK
  2. name varchar
  3. phone int
  4. city varchar
  5. 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 :

  1. John 0123456 Paris
  2. Jake 0255664 Montreal
  3. Jane 0165656 London
  4. Fred 0164465 Toronto
  5. Joan 0556494 Barcelona
  6. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!