代码之家  ›  专栏  ›  技术社区  ›  zlatan

count():参数必须是数组或在项目中实现可数错误的对象

  •  0
  • zlatan  · 技术社区  · 6 年前

    我目前正在从事一个拉威尔项目,我正在学习一门课程。一切都进行得很顺利,直到我不得不在我的项目中加入“雄辩有力”这个词。该软件包工作正常,但现在我的项目中出现以下错误:

    count():参数必须是数组或实现可数的对象

    @if($comments->count() > 0)
       @forech($comments as $comment)
         //displaying single comment data
      @endforeach
    @endif
    

    现在我的问题是,为什么现在会出现这个错误。可能是因为我在我的项目中做了“composer update”,它将我的PHP版本更新到了7.2,而该版本中存在count()问题吗?我猜是“>=”sign更改了我的PHP版本。我当前的laravel项目配置:

    "php": ">=5.5.9",
        "laravel/framework": "5.2.*"
    

    5 回复  |  直到 6 年前
        1
  •  1
  •   zlatan    6 年前

    我唯一可以绕过这个问题的方法是,在“vendor\laravel\framework\src\Illuminate\Database\Eloquent\Builder.php”中编辑错误行1185,使用:

    $originalWhereCount = is_array($query->wheres) ? count($query->wheres) : 0;
    

        2
  •  0
  •   Bruno Francisco    6 年前

    https://laravel.com/docs/5.6/collections#method-count

    这会让你

    @if(count($comment)>0)
       //displaying comments
    @endif
    

    @if($comment->count() > 0)
    //displaying comments
    @endif
    
        3
  •  0
  •   Gurpal singh    6 年前

    你可以试试这个

    $comment = comment::get()->all();
    
    @if(count($comment)>0)
      //displaying comments
    @endif
    
        4
  •  0
  •   Marcin Nabiałek    6 年前

    所以首先,你不应该在你的控制器中使用:

    $comment = Comment::all();
    

    但是

    $comments = Comment::all();
    

    把这个传给

    return view('some_view', compact('comments'));
    

    现在在您看来,您应该使用:

    @if ($comments->count())
       @foreach ($comments as $comment)
          // here you display single comment data for example {{ $comment->text }}
       @endforeach
    @endif
    
        5
  •  0
  •   Varun.Kumar    6 年前

    在这里你可以做一些things:-

    1. 你可以降级你的PHP版本。
    2. 您可以在执行query:-

    从此处更改

    $comment = Comment::get();
    

    为了这个

    $comment = Comment::get()->toArray();