Empty array don't appear as empty in Laravel blade - php

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

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.

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

Get specific key value from array

I'm trying to get a specific value using an array key, but I can't seem to figure out how to make it work.
$Array = Array(
"key1" => "value1",
"key2" => "value2"
);
Let's say I want to get the value of "key1" only, and I return the array with the view.
return view("myview")->with("arraytoprint", $Array);
And I try it with blade but I get Trying to get property of non-object...
#foreach($arraytoprint as $arr)
{{ $arr->key1 }}
#endforeach
How can this be achieved?
The error tells you that you are trying to get property of non-object but you are passing in an array. The -> notation is used for accessing properties in objects, not arrays.
You access keys in PHP arrays using the square bracket notation instead, as below:
$arr['key1']
In your example you also have no need for the foreach loop if you want to access the keys directly, just simply do:
{{ $arraytoprint['key1'] }}
If you do want to loop over the values then you can just do the below:
#foreach($arraytoprint as $value)
{{ $value }}
#endforeach
And for completeness sake, if you want the keys too you can do:
#foreach($arraytoprint as $key => $value)
{{ $key }} : {{ $value }}
#endforeach
In Laravel 5, passing data to the view is now done like this :
return view("myview", ["arraytopoint"=>$Array]);
and access in blade view like this:
{{$arraytopoint['key1']}} inside #foreach loop
or test value of variable like this :
<?php print_r($arraytopoint['key1']); ?>

Blade foreach cast output to an object

I am trying to figure out how I can give my data output in the blade file, the Laravel look;
like $data->name
But I can't get the output to be casted as an object. I think I have to make an array of the data before I can loop it proper in a foreach but this doesn't feel like the right way.
I am relatively new to Laravel and I want to do this the nice way, can someone point me in the right direction? Thanks in advance
Controller:
$data = collect($this->api->organization->index())->toArray();
return View::make('pages.organization.index', array('data' => $data[0]));
View:
#foreach($data as ((object)$organization))
{{ $organization->name }}
#endforeach
I know this will not work, but I think it illustrates my question a little bit.
EDIT
What I didn't realize is that $data = collect($this->api->organization->index()); is returning an array with all the data arrays inside because I didn't name it in my return like this:
return (object)['all' => $data];
After adding all I could reference the code inside my view like I wanted to. I know this is not a very detailed answer, if you run into the same problem message me I'll edit the answer.
Object:
$data = collect($this->api->organization->index());
#foreach($data as $organization))
{{ $organization->name }}
#endforeach
Array:
$data = collect($this->api->organization->index())->toArray();
#foreach($data as $organization))
{{ $organization['name'] }}
#endforeach

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