Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Limiting the results in Blade foreach loop

Set limit in foreach loop in Blade file in Laravel

In this tutorial, I will give you an example of “How to Set a limit in foreach loop in the Blade file in Laravel“, So you can easily apply it with your laravel 5, laravel 6, laravel 7, laravel 8, and laravel 9 applications.

First, what we’re doing here, This is the example :

Limiting the results in Blade foreach loop

set limit in foreach loop in laravel

Set limit in foreach loop using take() function in Laravel

There are different ways to limit the collection, we can use limit in the controller and we can also use array slice in the blade file.

But sometimes we have set the limit directly in the blade file according to the result so we use directly limit the foreach loop in the blade file in Laravel.

We use the take() function in the blade file which will help to get data from a database table with a limit.

Brands Table:

We have a brand table and we have 10 records on the table.

brand table

web.php:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BrandController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/limit-product', [BrandController::class,'list']);

BrandController.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use\App\Models\Brand;

class BrandController extends Controller
{
      public function list(){
        $brands = Brand::orderBy('brand_name')->get();
        return view('list',compact('brands'));
    }
}

list.blade.php:

Limiting the results in the Blade file foreach loop

     <div class="container">
         <div class="col-lg-12 margin-tb">
            <div class="pull-left">
               <h3 style="color: #BE206B;">Limiting the results in Blade foreach loop - Laravel</h3>
            </div>
         </div>
      <table class="table table-bordered">
         <tr>
            <th>ID</th>
            <th>Brand name</th>
         </tr>
        @foreach($brands->take(5) as $key => $brand)
         <tr>
            <td>{{$key+1}}</td>
            <td>{{ $brand->brand_name }}</td>
         </tr>
        @endforeach
      </table>
   </div>
   

set limit using take() function in blade file in laravel

Run The Application :

http://127.0.0.1:8000/limit-product

In this article, we learned “Set limit in foreach loop using take() function in Laravel example, I hope this article will help you with your Laravel application Project.

Read also:- Combine array in laravel in the blade file example.