John Davidson

php - how to limit data inside foreach value if there is condition applied?

0 comments
Message:


In my blade template, I have applied foreach loop . And the data from foreach loop is from relation that I want to show. In that single loop I have to show three different type of data by applying IF condition. From my backend i have passed whole collection without limiting or pagination to front. And i want to limit data in my blade template.


blade view

@foreach($ft->menus as $menu)
@if($menu->foodtype_id == $ft->id)
//want to limti data here
// for every food type i want to show 6 data
@endif
@endforeach

controller page


$data['food_type'] = FoodType::with('menus')->get();


My Answer:
>items as $item)
@if($item->type == 'type1')
// show type1 data
@elseif($item->type == 'type2')
// show type2 data
@elseif($item->type == 'type3')
// show type3 data
@endif
@endforeach

__In order to limit the data inside the foreach loop based on a condition, you can use a counter variable to keep track of the number of items displayed for each type. Here's an example of how you can achieve this:__

php
@php
$type1Count = 0;
$type2Count = 0;
$type3Count = 0;
@endphp

@foreach($ft->items as $item)
@if($item->type == 'type1' && $type1Count < 5)
// show type1 data
@php $type1Count++; @endphp
@elseif($item->type == 'type2' && $type2Count < 5)
// show type2 data
@php $type2Count++; @endphp
@elseif($item->type == 'type3' && $type3Count < 5)
// show type3 data
@php $type3Count++; @endphp
@endif
@endforeach


__In this example, we have added counter variables for each type of data and limited the display to 5 items for each type. You can adjust the limit as needed.__

Rate this post

4 of 5 based on 7292 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us