Split an Eloquent Collection by half in Laravel

Created at 18-Nov-2021 , By samar

Split an Eloquent Collection by half in Laravel

We will use programming in this lesson to attempt to solve the "Split an Eloquent Collection by half in Laravel".

Sometimes you have to split an Eloquent collection by half in Laravel view. You can use chunk method with ceil to divide records in two equal portion and display in view file using foreach() loop.
  • Divide eloquent collection in two equal portion and display in 2 columns of a row in Laravel view

    //routes\web.php
    Route::get('/get-users', function(){
        $allUsers = App\Models\User::all();
        return view('home', compact('allUsers'));
    });
    
    //resources\views\home.blade.php
    <div class="container">
        <div class="row">
        @foreach($allUsers->chunk(ceil($allUsers->count()/2)) as $users)
            <div class="col-md-6">
                @foreach($users as $user)
                <p> {{ $user->name }} </p>
                @endforeach
            </div>
        @endforeach
        </div>
    </div>
    

    This code snippet will help you to display the records in two columns of a row with equal numbers of items. It will always be 1 element larger in the event that the array contains an odd number of elements.

    You have to add the bootstrap CDN in your view file to display these two columns side by side. You can also display records in three to four equal columns in by changing value form 2 to 3 or 4 as per your requirment in ceil() method.

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.