I’m trying to retrieve data from database and display all the data using foreachloop. Im getting first row data easily without foreach loop but whenever I try using loop the error displays "foreach() argument must be of type array|object, string given"
This is my Controller Code
class dbcontroller extends Controller
{
/**
* Display a listing of the resource.
*
* @return IlluminateHttpResponse
*/
public function index()
{
$posts = DB::table('table1')->get();
$d = $posts[0]->Name;
$a =$posts[0]->Age;
return view('db',compact('d','a'));
}
}
And my Blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
@foreach ($d as $user => $data)
<p>This name {{ $data->name }}</p>
@endforeach
{{-- <p>Name is {{$d}} & Age is {{$a}}</p> --}}
</body>
</html>
2
Answers
You should bring $posts for your foreach.
controller:
in blade:
The get() method always returns a collection which can be used in foreach loop. Whereas The first element of get() will return a single model instance. Again, you are just sending a single attribute of that model to view not the collection itself. You can not just run any loop on single attribute. This is basic PHP.
this will not work
Following can be true for your scenario:
Controller:
blade:
For references
https://laravel.com/docs/9.x/queries#retrieving-all-rows-from-a-table