Laravel @foreach 上的解析错误

Laravel Parse error on @foreach

我正在关注视频 Laravel 5.4 From Scratch: Eloquent Relationships and Comments 并遇到此错误:

Parse error: syntax error, unexpected ')', expecting '['

当我尝试复制视频并输入时,我明白了:

@foreach ($film->comment as comment)

<p>{{$comment->body}}</p>

@endforeach

这是错误页面上突出显示的代码部分:

<?php $__currentLoopData = $film->comment; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as comment): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>

然而,当我只输出 {{$film->comments}} 时,它确实给了我一个结果:

[{"id":1,"film_id":"1","body":"I loved this film!","created_at":null,"updated_at":null}]

我有一部电影table和评论table。在修补程序中,它显示为我想要的,例如

>>> $c = App\Comment::first();
=> App\Comment {#751
     id: "1",
     film_id: "1",
     body: "I loved this film!",
     created_at: null,
     updated_at: null,    }
>>> $c->film;
=> App\Film {#746
     id: "1",
     title: "The Godfather",
     director: "Francis Ford Coppola",
     description: "It stars Marlon Brando and Al Pacino as the leaders of a fictional New York crime family. The story, spanning 1945 to 1955, chronicles the family under the patriarch Vito Corleone (Brando), focusing on the transformation of Michael Corleone (Pacino) from reluctant family outsider to ruthless mafia boss.",
     date: "1972-03-24",
     created_at: null,
     updated_at: null,    }

以下是我的模型:

评论模型:

class Comment extends Model

{
    public function film()
    {
        return $this->belongsTo(Film::class);
    }
}

胶片型号:

class Film extends Model
{
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

非常感谢任何帮助!

@foreach ($film->comments as $comment)
<p>{{$comment->body}}</p>
@endforeach

首先确保 $film->comments 不为空并添加

@if( count($film->comments) > 0 ) 
   @foreach($film->comments as $comment)
      <p>{{$comment->body}}</p>
   @endforeach
@endif