Rezrazi
Rezrazi

Reputation: 895

Laravel slice collection after an element

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.

Upvotes: 1

Views: 16303

Answers (1)

Saravanan Sampathkumar
Saravanan Sampathkumar

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

Related Questions