Invalid argument supplied for foreach()
Personally I find this to be the most clean - not sure if it's the most efficient, mind!
if (is_array($values) || is_object($values))
{
foreach ($values as $value)
{
...
}
}
The reason for my preference is it doesn't allocate an empty array when you've got nothing to begin with anyway.
Error code Invalid argument supplied for foreach() when using json_encode (oop, php)
Besides the typo, to json_encode an array of objects your need to make an exporter method which returns an array of each property or implement JsonSerializable
<?php
class Post implements JsonSerializable {
protected $whatIs = ' ';
protected $whoIs = ' ';
protected $whenIs = ' ';
function __construct($what,$who,$when){
$this->whatIs=$what;
$this->whoIs=$who;
$this->whenIs=$when;
}
public function jsonSerialize()
{
return get_object_vars($this);
}
}
$arr = [];
$arr[] = new Post(1,2,3);
echo json_encode($arr);
Result:
[{"whatIs":1,"whoIs":2,"whenIs":3}]
Invalid argument supplied for foreach() Invalid Argument
It seems that your array $prod
is empty.
Add a condition empty() before foreach
like this:
if (! empty($prod)) {
foreach ($prod as $key => $value) {
// Your Code
}
}
else {
// No records found
}
This will check if the array provided to foreach
is not empty and loop over it only if it has records.
Thus, it will not show any errors/warnings.
Also, please go through your code and check why $prod
is not getting data.
Is it a condition that is causing no data or there is some error.
That will solve this problem permanently along with above solution.
invalid argument supplied for foreach() laravel relationship
I think you helper returns void because no book was found with that ISBN.
I think it should look like this btw
function getCommentsByISBN($isbn)
{
if ($book = Book::where("ISBN", $isbn)->first()) {
return $book->comments;
}
}
and in your blade your top should look like
@php
$comments = getCommentsByISBN(session("isbn")) ?: [];
@endphp
@foreach($comments as $comment)
<div class="form-group">
/// Rest of the code
Related Topics
Adding Multiple Items to Woocommerce Cart at Once
How to Wrap Long Lines Without Spaces in HTML
Convert to Date Format Dd/Mm/Yyyy
Php's File_Exists() Will Not Work for Me
Yii2:Activequery Example and What Is the Reason to Generate Activequery Class Separately in Gii
How to Access Discriminator Field from PHP in Doctrine2
How to Install the Intl Extension for Twig
Redirecting Wordpress's Login/Register Page to a Custom Login/Registration Page
Highlight Multiple Keywords in Search
Php: How to Generate a Hmacsha256 Signature of a String
Checking for an Empty Result (Php, Pdo, and MySQL)
Changing a Global Variable from Inside a Function PHP
How to Write to Error Log File in PHP
How to Check for a Specific Type of Object in PHP
PHP - Most Lightweight Psr-0 Compliant Autoloader
Unescape or HTML Decode in Twig (PHP Templating)