-2

working with Laravel 8 and I have following view file with controller index.blade.php

<div class="row">
    <div class="col-md-12">
        <table class="table">
            <thead>
                <th>#</th>
                <th>Title</th>
                <th>Body</th>
                <th>Created At</th>
                <th></th>
            </thead>

            <tbody>
                @foreach ($posts ?? '' as $post)

                <tr>
                    <th>{{$post->id}}</th>
                    <td>{{$post->title}}</td>
                    <td>{{ substr($post->body,0,50)}}{{ strlen($post->body) > 50 ? "..." : ""}}</td>
                    <td>{{ date('M j, Y', strtotime($post->created_at))}}</td>
                    <td><a href="{{route('posts.show',$post->id)}}" class="btn btn-default btn-sm">View</a><a href="{{route('posts.edit',$post->id)}}" class="btn btn-default btn-sm">Edit</a></td>
                </tr>
              @endforeach
            </tbody>
            
        </table>
    </div>
</div>

and Controller

public function index()
    {
        $posts = Post::all();
        return view('posts.index');
    }

but I got following error message

ErrorException Invalid argument supplied for foreach() (View: F:\2020 technologies\laravel\blog\resources\views\posts\index.blade.php)

what is wrong with this. how could I fix this matter?

porup
  • 15
  • 1
  • 2
  • 4
    Welcome to SO ... `''` (an empty string) would not be something that `foreach` would accept – lagbox Nov 12 '20 at 13:21
  • Does this answer your question? [Invalid argument supplied for foreach()](https://stackoverflow.com/questions/2630013/invalid-argument-supplied-for-foreach) – El_Vanja Nov 12 '20 at 13:22
  • your controller isn't passing any data to the view ... but are you expecting `$posts` to be something other than a Collection in the view (if the controller was passing it) – lagbox Nov 12 '20 at 13:24
  • What have you tried to debug the problem? – Nico Haase Nov 12 '20 at 13:27

1 Answers1

1

You can pass data to the view using the with method.

Try this:

public function index() 
  {  $posts = Post::all();
      return view('posts.index')->with(compact('posts'));
   }
paranoid
  • 6,799
  • 19
  • 49
  • 86