I’m receiving an error while using the foreach loop in the blade.php. I have tried many things but everytime i recevie the same error while using foreachloop
Here is my code
Post.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul>
@foreach($datafromtestmodel as $rows)
<li>
<p>{{$rows['name']}}</p>
<p>{{$rows['company']}}</p>
</li>
@endforeach
</ul>
</body>
</html>
Controller Function
public function index()
{
$testmodeldata = new testmodel;
$datafromtestmodel = $testmodeldata ->abc();
return view('post', compact('datafromtestmodel'));
}
Model Function
public function abc(){
$blabla = ['name' => 'abc', 'company' => 'abc company'];
return $blabla;
}
Route
Route::get('post','PostController@index');
2
Answers
As I can see, ‘$datafromtestmodel’ will be single dimensional array, but in blade file, you have treated it as multi dimensional array. This can be fixed in two way. Either return multi dimensional array from model function like this.
Or you have to update it in your blade file.
Your
$datafromtestmodel
contains['name' => 'abc', 'company' => 'abc company']
directly.so when you loop into each item is not an array but directly values (‘abc’ at first iteration, then ‘abc company’ at second iteration). They are not array.
To get why you expect your abc function should return an array of array values