Home > Software engineering >  foreach() argument must be of type array|object, string given Laravel
foreach() argument must be of type array|object, string given Laravel

Time:12-05

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 \Illuminate\Http\Response
     */
    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>

CodePudding user response:

You should bring $posts for your foreach.

controller:

return view('db', compact('posts'));

in blade:

@foreach ($posts as $post)
    <p>{{ $post->name }}</p>
@endforeach
  • Related