I'm Getting This Error Code: Invalid Argument Supplied for Foreach()

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



Leave a reply



Submit