How to limite foreach loop - php

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

Related

Loop interation inside #each directive

I'm trying to iterate over a loop of items which is being included via the #each directive in Laravel Blade.
When I use a regular #foreach loop, this works perfectly fine and I can iterate over odd/even records, but when using #each, this concept doesn't seem to be working.
Am I doing something wrong or is this expected behaviour of the #each directive?
My code is as follows:
splits.blade.php
<section>
#each('_partials/components.split', $page->splits, 'split')
</section>
split.blade.php
<article
#if ($loop->odd)
style="background-image: url('placehold.it/1920x400');"
class="bg-cover bg-center"
#else
class="bg-white"
#endif
>
</article>
Any help would be greatly appreciated.
Many thanks
Matt
Each doesn't include $loop variable in blade file automatically but passes $key variable.
So you can write:
<article
#if ($key % 2 == 0)
style="background-image: url('placehold.it/1920x400');"
class="bg-cover bg-center"
#else
class="bg-white"
#endif
>
</article>
The each directive does not have the $loop variable like foreach.
However, it does send the key of every item in the provided array to the view. So if you did not set custom keys, the $key variable should contain a value from 0 to the length of your array.
Just found this out by looking in the source code.

Empty array don't appear as empty in Laravel blade

Right now I'm trying to check when the view receives an empty array.
#if(! empty($array))
// Section content goes here...
#foreach($array as $value)
// All table data goes here...
#endforeach
#endif
The code as it is above seems to still run when the $array is empty and causes an exception.
When I try to dump the array with {{ dd($array) }} I get $array = [].
Sounds like you might be having a collection. You could simply do count($array) to check amount of records in the array. It would look something like this:
#if(count($array))
// Section content goes here...
#foreach($array as $value)
// All table data goes here...
#endforeach
#endif
The section should now be hidden. If you wish to only skip the foreach when there is nothing in the array you could do this:
// Section content goes here...
#forelse($array as $value)
// All table data goes here...
#empty
// Optional message if it's empty
#endforelse
Which would output the section content and check if the array has any values before it foreach it.
You can read more about loops within blade files in the Laravel documentation.
Is it possible your array is a collection?
Try using a #forelse, this will check if the array or collection is empty and display another block instead. For example:
#forelse($array as $value)
{{ $value }}
#empty
array is empty
#endforelse

Blade laravel variable value type?

I'm new to laravel
Just being curious,
Suppose I make an array in a view page
myView.blade.php
Suppose:
$array = [
1, 2, 3
];
in the same page, I want to loop it with "blade" foreach
suppose:
#foreach($array as $value)
<span id="{{$value}}">{{$value}}</span>
#endforeach
but, I get an error like this.
ErrorException in 1ed42d9dadecab7c54e086f573c4cbad6576e7c3.php line 63:
Trying to get property of non-object...
what's happened? what type of variable actually blade converts?
Any question will highly appreciated! :)
First of all, it's better if you just pass the data to your view files from controller.
But, if you still want to do that, and you are using Laravel 5.3, you can do it like this:
#php
$array = [
1, 2, 3
]
#endphp
and then loop it:
#foreach($array as $value)
<span id="{{$value}}">{{$value}}</span>
#endforeach
Make, sure that you declare the $array array before the loop.
Have a look at the Service Injection and View Composers on Larave's documentation aswell.
Actually, I don't know what do you want? But recommendly, you should init your array at controller, through it to view and foreach.
In controller,
return view('your view path', ['array' => $array]);
In blade
#foreach($array as $value)
<span id="{{$value}}">{{$value}}</span>
#endforeach
Hope it could help, thanks.

php Issue with Intro.js using it in a foreach loop

I have decided to use Intro.js to create a guide for my website.
But I have this issue. If I put Intro.js in a loop it works for all the rows it generate. so each loop generate 50 rows dynamically from result from DB and hence generate 50 intro.js.
Is there way to break; or stop Intro.js not go through the entire loop and focus on one row instead?
#foreach($providers as $key => $provider)
<tr data-intro="{{ TL::helpdesk('viewvilkareachrowdescription') . $provider->name }}"></tr>
#endforeach
Hope its possible? please help anyone?
you can use an if statement to do something on only one row and print the others.
here is an example :
#foreach($providers as $key => $provider)
#if ($provider->name == 'any_name')
... // << case focus on one row
#else
<tr data-intro="{{ TL::helpdesk('viewvilkareachrowdescription') . $provider->name }}"></tr>
#endif
#endforeach
and here is a link to documentation about Blade Templating : https://laravel.com/docs/5.0/templates

error of foreach with empty array

I'm working in Laravel 5 using Blade as motor of templates. I'm passing an array from the controller to the view, and I noticed that when I loop on it using the foreach clausule and the array is empty it gives error, exactly this:
Invalid argument supplied for foreach()
I had the same error in the controller and I fix it temporaly making:
if(count($student)!=0)
I said temporaly because I don't think it this the best way to do it.
The code in the controller is:
foreach($students as $student){
if(count($student->contracts)!=0)
foreach($student->contracts as $contract){
//something
}//end foreach
}//end foreach
I made some operations over the arrays, and then I send them to the view:
return view('myview')->with(['students'=>$students]);
The array is passing to the view correctly. I said is the foreach, beacause earlier I had the database full of registers and it worked fine, but now I have some students that doesn't have contracts and then I got that error. But, in the view I have the same error. So, it's normal? how could I fix it in a better way? why when the array is empty the foreach clausule gives that error?
PHP will not return that warning if the array contained at $student->contracts is empty. It will return it if it is of an invalid type (i.e. not an array).
Rather than checking the count() of $student->contracts, you'd be better to check if it's actually an array, as follows:
foreach($students as $student)
{
// Make sure that $student->contracts is actually an array (to bypass errors):
if( is_array($student->contracts) )
{
// Now loop through it:
foreach( $student->contracts as $contract)
{
// Do something here
}
}
}
Try this
$people = [
"Person A", "Person B", "Person C"
];
return view ('pages', compact('people'));
and loop through it like this:
#if (count($people))
<h3>People:</h3>
<ul>
#foreach($people as $person)
<li>{{ $person }}</li>
#endforeach
</ul>
#endif

Categories