
Split an Eloquent Collection by half in Laravel
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.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
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.
Random Code Snippet Queries: Laravel
- How to increment column value of table in Laravel
- How to get laravel errors folder in views directory in laravel
- Drop foreign key column in Laravel using migration
- Laravel save object to database
- How to pass external link in laravel blade to anchor tag
- Create project factory and seed data in laravel
- How to Run CRON Job on LIVE SERVER on Cpanel in Laravel Project
- How to return a column with different name in Laravel
- Class 'App\Http\Controllers\User' not found
- Rename Pivot Table in Laravel
- How to display order by null last in laravel
- Get laravel version
- Method Illuminate\Database\Eloquent\Collection::lists does not exist
- How to insert dynamic values to additional column with pivot column in pivot table on multiple records
- Get id of last inserted record in laravel
- Define variable and use in Laravel controller method
- Symlink(): No such file or directory
- How to get session in blade Laravel ?
- How to send ID to another page in Laravel
- How to change default timestamp fields name in Laravel
- If condition in foreach loop in laravel
- How to get path from current URL in Laravel
- How to get column names from table in Laravel
- Json encode method in laravel
- How to validate URL with https using regex in laravel