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.

Answers 1
  • Divide eloquent collection in two equal portion and display in 2 columns of a row in Laravel view

    Route::get('/get-users', function(){
        $allUsers = App\Models\User::all();
        return view('home', compact('allUsers'));
    <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>

    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