skip to Main Content

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


  1. You should bring $posts for your foreach.

    controller:

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

    in blade:

    @foreach ($posts as $post)
        <p>{{ $post->name }}</p>
    @endforeach
    
    Login or Signup to reply.
  2. 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

    $d = $posts[0]->Name;
    $a =$posts[0]->Age;
    
    return view('db',compact('d','a'));
    

    Following can be true for your scenario:

    Controller:

    class Dbcontroller extends Controller
    {
        /**
         * Display a listing of the resource.
         *
         * @return IlluminateHttpResponse
         */
        public function index()
        {
            
            $posts = DB::table('table1')->get();
    
            return view('db',compact('posts'));
        
        }
    }
    

    blade:

    <!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 ($posts as $post)
                <p>{{ $post->someAttribute }}</p>
            @endforeach
    
    </body>
    </html>
    

    For references

    https://laravel.com/docs/9.x/queries#retrieving-all-rows-from-a-table

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search