How to exclude items in foreach loop - php

I'm trying to display a specific set of references on my laravel page by iterating through an foreach loop and styling odd and even iterations differently with #class loop odd / loop even.
However I as I begin the foreach loop with an #if, only some make it into the loop while some are skipped, which messes up my odd / even (e.g. #1, #2 and #4 make it into the loop which means I have two elements styled with loop even.
How can I skip the ones that don't make it into the loop so I can display the result with alternating styling?
#foreach ($references as $reference )
#if(isset($reference['is_startpage'])
&& $reference['is_startpage'] != 1
&& isset($reference['content']['featured'])
&& $reference['content']['featured'] == 1)
<div #class([
'row py-5' => $loop->odd,
'row flex-row-reverse py-5'=> $loop->even,
])></div>
#endif
#endforeach

As you say, not every loop iteration prints the <div> element, so $loop->even and $loop->odd variables are not valid in your case for implementing that specific logic. However, there are many ways to achieve what you want. The first way that comes into my mind is using a specific counter for that, i.e.:
#php $featuredCount = 0; #endphp
#foreach ($references as $reference)
#if(
isset($reference['is_startpage'])
&& $reference['is_startpage'] != 1
&& isset($reference['content']['featured'])
&& $reference['content']['featured'] == 1
)
#php $featuredCount++; #endphp
<div #class([
'row py-5', // These two are always present, no need to conditionally rewrite them
'flex-row-reverse' => $featuredCount % 2 == 0, // 'Even' check
])></div>
#endif
#endforeach

Related

Prevent foreach from loop html tag multiple time in blade laravel

I'm trying to loop data using foreach and I want to skip the html tag after the first item being looped.
I've tried like the code bellow, but the html tag <p> still being looped multiple time. What I want is the <p> tags only looped once
#foreach ($store_icon as $key => $icon)
#if ($key < 1)
<p class="available-at">Also available at:</p>
#endif
#endforeach
Result example:
What I want is like this:
Also Available at
- Product 1
- Product 2
But using the code above it resulted like this:
Also Available at
- Product 1
Also Available at
- Product 2
Thanks
I am not sure why it is not working, It must work and working the same code for as well, you can try --
#foreach ($store_icon as $key => $icon)
#if ($key == 0)
<p class="available-at">Also available at:</p>
#endif
#endforeach
OR you can use like this
#if(!empty($store_icon))
<p class="available-at">Also available at:</p>
#foreach ($store_icon as $key => $icon)
#endforeach
#endif
Whats problem? Just take it out from loop.
<p class="available-at">Also available at:</p>
#foreach ($store_icon as $key => $icon)
#endforeach

Min 3 elements in foreach Laravel

I have a collection where can be maximum 3 elements. Can be 1 element, can be 2 elements. If I have only 1 element, or 2 elements in collection I need check it and add html.
My code:
#foreach($collections->take(3)->get() as $collection)
{{ $collection->name }}
#if($collections->count() == 1)
<div>empty</div>
#endif
#if($collections->count() == 2)
<div>empty</div>
<div>empty</div>
#endif
#endforeach
I need get this result:
Collection name
empty
empty
Or If I have 2 elements in collection, I need get result:
Collection name
Collection name
empty
If I have 3 elements in collections I need get:
Collection name
Collection name
Collection name
How I can make it?
I don't see a reason why your current code wouldn't work, but you can have a go at the following approach.
Loop through the collection limited by 3 as you were, then afterwards, run a for loop - if the $collections->count() is 2, then 3-2 = 1, so you get 1 iteration of the for-loop. If the count is 3 or higher, the condition of the for loop is never true, and it doesn't print anything.
#foreach($collections->take(3)->get() as $collection)
{{ $collection->name }}
#endforeach
#for ($i = 0; $i < 3 - $collections->count(); i++)
<div>empty</div>
#endfor

How to limite foreach loop

How to print limited data with FOREACH
I have 10 data in db but, i want to print only first 3 data with foreach.
Also i tried and used array_slice() method, but next i got some errors.
Thank you!
#foreach($products as $_product)
//there is Html code... with variables
#foreach
I tried : #foreach(array_slice($products, 0, 2) as $_product). and i got:
array_slice() expects parameter 1 to be array, object given.
You can use limit(3) in your eloquent or take(3)
Or if you need to make it in blade use $loop variable
Like this
#if($loop->iteration <=3)
#continue
Or in your controller
Product::limit(3)->get();
Product::take(3)->get();
If u use it in controller there will be no need to check in your blade view
Just use the #break; statement once you've printed however many you want - it will jump you out of the foreach loop.
so something quick i can think of this:
#foreach($products as $_product)
//there is Html code... with variables
#if($loop->iteration == 3) //Thanks to the response of #MohammedAktaa
#break
#endif
#foreach
Although I think it should be best to limit the results from the query to the database.
Ordering, Grouping, Limit, & Offset

How to output odd and even rows in laravel

I have a project where I'm pulling posts from the database and rendering on the home page view. Like a Blog. (On the home page I limit this to 3 posts)
I have 6 rows in the table, and would like to style the output based on ODD and Even rows.
Here is my controller:
public function index()
{
$counter = Post::count();
$posts= DB::table('posts')->orderBy('id', 'DESC')->limit(3)->get();
return view('home',compact('posts','counter'));
}
I want the even numbered rows to have <div class="even"> and the odd numbered rows to have <div class="odd">
When I dd on $counter I get the value 6. This is correct. I have 6 rows in the table.
What I'm currently trying based on other articles I've found:
#foreach ($posts as $post)
#if($counter % 2 == 0)
<div class="even">{{$post->title}}</div>
#else
<div class="odd">{{$post->title}}</div>
#endif
This doesn't do anything. Still outputs the rows as 6,5,4,3,2,1
So how can I write the IF Statement inside my Foreach loop to say...
if ($counter == odd)
<div class="odd">
else
<div class="even">
The order I'm looking for is:
Odd
Even
Odd
Even
$counter is a static variable, so calling $counter % 2 == 0 will always show the same result.
If you are using Laravel 5.4+, there is a $loop variable included in the #foreach(). So you can access your mod division within the loop.
Here is the example for Laravel 5.4+
#foreach ($posts as $post)
#if($loop->iteration % 2 == 0)
<div class="even">{{$post->title}}</div>
#else
<div class="odd">{{$post->title}}</div>
#endif
#endforeach
Laravel 5.8.5 add even and odd Boolean flags in the Blade loop variable
Now you can use:
$loop->even or $loop->odd
Instead of
$loop->iteration % 2
Reference link
You need to increment the counter on each iteration.
#php
$counter = 1;
#endphp
#foreach ($posts as $post)
#if($counter % 2 == 0)
<div class="even">{{$post->title}}</div>
#else
<div class="odd">{{$post->title}}</div>
#endif
#php
$counter++;
#endphp
#endforeach

How would i use php / blade to change div classes

I am using blade for the first time, and i need to change the styling of this div element depending on how many properties are available. I need to write an if statement which hides the div if equal or less than one and add a different class if equal to 2.
how would i write this using blade or php?
#if (isset($participatingProperties) && !empty($participatingProperties) && is_array($participatingProperties))
<?php $i = 0; ?>
#foreach ($participatingProperties as $key => $property)
#if ($i++ % 3 === 0)
<div class="item item2 {{ $i < 3 ? 'active' : '' }}">
#endif
What I understand is :
You have a $participatingProperties array and one div to print.
When it has 0 or 1 element, nothing happens.
When it has 2 elements, the div prints with a specific style.
When it has 3 or more elements, the div prints with another style.
(No rule for more than 3 elements).
I would keep it simple with count :
#php($count = count($participatingProperties))
#if ($count > 1)
<div
class="{!! ($count == 2) ? 'class-2' : 'class-3-or-more' !!}"
>
div content
</div>
#endif
If you don't need a specific style for every amount, it's even simpler :
#if (count($participatingProperties) > 1)
<div class="myclass">
div content
</div>
#endif
Using both empty and isset is redundant. And I think you should not have to check if $participatingProperties is an array, instead make sure it always is in your backend. If you return at least an empty array, count will return 0.

Categories