【问题标题】:Invalid argument supplied for foreach() Laravel 5.5为 foreach() Laravel 5.5 提供的参数无效
【发布时间】:2019-10-05 23:42:56
【问题描述】:

我有两个表,用户和帖子表在 Laravel 5.5 中使用一对多关系链接在一起。我只想显示与登录用户相关的帖子。

我有 PostController,我在其中获取当前用户登录并将其传递给视图 index.php。在 index.php 视图中,我尝试使用@foreach 获取和循环与登录用户关联的帖子。

请参阅下面的示例代码。

后控制器

public function index()
{
    $currentuser = Auth::user();
    return view('posts.index')->withCurrentuser($currentuser);
}

index.php 视图

@foreach ($currentuser->posts as $post)
        <tr>
            <td>{{ $post->id }}</td>
            <td>{{ $post->title }}</td>
            <td>{{ substr(strip_tags($post->body), 0, 40) }}{{ strlen(strip_tags($post->body))>40 ? "..." : "" }}</td>
            <td>{{ date('M j, Y', strtotime($post->created_at)) }}</td>
            <td><a href="{{ route('posts.show', $post->id) }}" class="btn btn-outline-blue btn-sm">View</a>&nbsp;<a href="{{ route('posts.edit', $post->id)}}" class="btn btn-sm btn-outline-blue">Edit</a></td>

        </tr>

    @endforeach

User.php 模型

 protected $table = 'users';
    public function post(){
        return $this->hasMany('App\Post');
    }

Post.php 模型

public function users(){
    return $this->belongsTo('App\User');
}

我收到一个错误

为 foreach() 提供的参数无效

问题可能出在哪里?

【问题讨论】:

    标签: php laravel-5.5


    【解决方案1】:
    $currentuser->posts in Foreach 
    you used $currentuser->posts
    but "posts" is method in you model (user.php).
    so use it as method.
    Or use temp variable for foreach like..
    $posts = $currentuser->posts();
    foreach($post as $key=> $val)
    {
    }
    

    【讨论】:

      【解决方案2】:

      用户模型将方法定义为post(),但在foreach 中您将其称为-&gt;posts(复数)。试试@foreach ($currentuser-&gt;post()-&gt;get() as $post)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-09
        • 1970-01-01
        • 2015-06-29
        • 2022-01-27
        • 2018-02-26
        • 2017-11-26
        • 2021-12-25
        • 2018-10-31
        相关资源
        最近更新 更多