
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>
0This 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.
Random Code Snippet Queries: Laravel
- How to get path from current URL in Laravel
- Laravel 7 login error message not showing
- How to validate form input data in laravel
- Recursive function example code PHP Laravel
- How to Get records between two dates in Laravel
- The Pusher library requires the PHP cURL module. Please ensure it is installed
- Laravel route redirect not working
- How to check records exist in loaded relationship in Laravel blade view
- How to get id of next record in laravel
- Get the post details if it has at least one comment in comments table
- How to upload image in laravel 8
- Target class [HomeController] does not exist
- Display message with session flash using bootstrap alert class in laravel
- How to avoid duplicate entries in pivot table in Laravel
- Route prefix with auth middleware in laravel
- How to disable timestamps in laravel
- How to get query string value in laravel
- How to pass link from controller to view in laravel on ajax call
- SQLSTATE[23000]: Integrity constraint violation: 1022 Can't write; duplicate key in table
- Laravel create table migration with model
- Order by multiple columns in Laravel
- Save or update pivot table data with additional column in Laravel
- Conditional where clause in Laravel
- Get posts belongs to a specific user in Laravel
- Get id of last inserted record in laravel