首页 > 解决方案 > Laravel 8 中为 foreach() 提供的参数无效

问题描述

使用 Laravel 8,我有以下带有控制器 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>

和控制器

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

但我收到以下错误消息

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

这有什么问题。我该如何解决这个问题?

标签: phplaravel

解决方案


您可以使用该方法将数据传递给视图with

试试这个:

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

推荐阅读