Ruka Xing
Ruka Xing

Reputation: 642

Laravel chunk data

The problem is how to split em like same 5 parts in any case. So it means if i take 41. i just need split em 5 parts. Any inputs are must split 5 parts. and take of 5 them into each $collection. I was using chunk but I'm stuck please help.

Result

array:31 [▼
  0 => Question {#516 ▶}
  1 => Question {#517 ▶}
  2 => Question {#565 ▶}
  3 => Question {#566 ▶}
  4 => Question {#567 ▶}
  5 => Question {#615 ▶}
  6 => Question {#616 ▶}
  7 => Question {#617 ▶}
  8 => Question {#618 ▶}
  9 => Question {#619 ▶}
  10 => Question {#667 ▶}
  11 => Question {#668 ▶}
  12 => Question {#669 ▶}
  13 => Question {#670 ▶}
  14 => Question {#671 ▶}
  15 => Question {#672 ▶}
  16 => Question {#673 ▶}
  17 => Question {#714 ▶}
  18 => Question {#715 ▶}
  19 => Question {#764 ▶}
  20 => Question {#765 ▶}
  21 => Question {#766 ▶}
  22 => Question {#767 ▶}
  23 => Question {#768 ▶}
  24 => Question {#813 ▶}
  25 => Question {#814 ▶}
  26 => Question {#815 ▶}
  27 => Question {#816 ▶}
  28 => Question {#861 ▶}
  29 => Question {#862 ▶}
  30 => Question {#863 ▶}
]

Controller@create

dd($questions->all());

Update here is my Controller@create

that's how I'm taking questions from view.

$all = Request()->all();

        $questions = collect();
        $topicIds = [];
        foreach ($request->input('number') as $key => $value) {
            if (strlen($value) > 0) {
                $topicIds[] = $key;
                $items = Question::inRandomOrder()->where('topic_id', $key)->limit($value)->get();
                //dd($items);
                $questions = $questions->merge($items);
            }
        }

View

<div class="panel panel-default">
            <div class="panel-heading">
                Сэдэв сонголт
            </div>

            <div class="panel-body">
            @foreach ($duplicates as $duplicate)
            {{ $duplicate->topic->title }} нийт {{ $duplicate->total }} асуулт байна.<br>
            <input type="number" name="number[{{ $duplicate->topic->id }}]"></input><br><br>
            @endforeach
            <br/>

            </div>
        </div> 

Upvotes: 2

Views: 1165

Answers (2)

Sohel0415
Sohel0415

Reputation: 9853

Count the array of collection object first, then use chunk()

$chunks =  $questions->chunk(ceil(($questions->count())/5));
foreach($chunks as $chunk){
      //dd($chunk)  //here $chunk is your parted collection
      //to get the individual data of parted collections, make another foreach
      foreach($chunk as $q){
           //$q is a individual object
      }
}

How do I $questions split to 5 $collection: use this in your chunk() method

ceil(($questions->count())/5)

Upvotes: 1

Stojan Kukrika
Stojan Kukrika

Reputation: 312

You can make array of list of collection using ->toAttay() then you can chunk data.

Upvotes: 0

Related Questions