【问题标题】:Facade\Ignition\Exceptions\ViewException count(): Parameter must be an array or an object that implements Countable (View:Facade\Ignition\Exceptions\ViewException count():参数必须是数组或者实现了Countable的对象(View:
【发布时间】:2020-02-02 17:37:04
【问题描述】:

我运行以下代码来显示我的一对多关系,但是我收到错误:Facade\Ignition\Exceptions\ViewException count():参数必须是数组或者实现了Countable的对象(查看:

这是我的代码:PostsController.php

public function show($id)
{
    $post = Post::find($id);
    $review = Post::find(1)->reviews()->where('title', 'posts_title')->first();
    //$review = Review::all();

    return view('posts.show', compact('post', 'review'));
}

Post.php

   protected $tables='reviews';

  function reviews(){

      return $this->hasMany('App\Review', 'title', 'post_title');

    }

从堆栈跟踪来看,错误就在这里:

    @if(count($review) > 1)

    @foreach($review as $reviews)

谁能帮忙?

【问题讨论】:

  • 您正在尝试遍历$review,但它是一个对象,因为您使用->first(); 获取它
  • 你知道first()get()all()之间的区别吗?

标签: laravel


【解决方案1】:

如果你使用 ->first() 你会收到一个对象,然后你既不能使用 count 也不能​​用 @foreach 迭代

所以这是你的错误:

// object
$review = Post::find(1)->reviews()->where('title', 'posts_title')->first();

// collection
$reviews = Post::find(1)->reviews()->where('title', 'posts_title')->get();

你可以在 $reviews 上使用

@if($reviews->count() > 1)

@foreach($reviews as $review)

【讨论】:

  • 我现在得到这个错误:ErrorException compact(): Undefined variable: review on line: -> return view('posts.show', compact('post', 'review'))。即使“审查”之前有效?
  • return view('posts.show', compact('post', 'reviews')); 如果您将变量重命名为 $reviews,则紧凑方法需要“reviews”作为参数
  • 真棒,有点工作,但它不显示我的数据。我的 SQL 表中有数据,但它没有输出任何东西(我对 laravel 有点陌生)所以请原谅我的错误
【解决方案2】:

PHP 中的 count() 方法需要可计数的对象或数组或集合。如果传递了任何其他数据类型,如字符串、null 或空值,它在 PHP 7.X 版本中严格抛出致命错误,但 PHP 5.x 只是发出警告并继续执行。

你可以通过使用空函数来避免这种情况

@if(!empty($review))

    @foreach($review as $reviews)

【讨论】:

  • 这有点用,但是我的帖子现在都没有出现
猜你喜欢
  • 2018-06-28
  • 1970-01-01
  • 2019-08-03
  • 2018-06-08
  • 2018-09-22
  • 1970-01-01
  • 2018-11-26
  • 2019-04-02
  • 2020-04-27
相关资源
最近更新 更多