0
votes

I'm currently working on a laravel project and I'm following a course. Everything was going just fine, untill I had to add "eloquent-sluggable" to my project. That package works just fine, but now I get the following error in my project:

count(): Parameter must be an array or an object that implements Countable

I'm using that count() function in my view:

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

Now my question is, why does that error gets shown now. Could it be because I did "composer update" in my project and it updated my PHP version to 7.2, and there is a count() problem in that version? I'm guessing the ">=" sign changed my PHP version. My current laravel project configuration:

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

But when I run "php -v" in my project, it shows that my PHP version is 7.2 now. Is there a way I could downgrade my PHP version without loosing my project files? Any help appreciated.

5
what is "$comment"? - Lars Stegelitz
You are passing object instead of array. Count( ) function only count the array. First of all convert it to array. - Gurpal singh
I'm putting all the comments in that variable in my controller: $comment = Comment::all(); - zlatan

5 Answers

1
votes

The only way I could get around this, is by editing error Line 1185 in 'vendor\laravel\framework\src\Illuminate\Database\Eloquent\Builder.php' with:

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

I don't know if this is bad for future project, but this was the only way I could get my project to work.

0
votes

What you are trying to do could be solved with https://laravel.com/docs/5.6/collections#method-count

This would turn your

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

to

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

You can try this one

$comment = comment::get()->all();

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

So first of all, you shouldn't use in your controller:

$comment = Comment::all();

but

$comments = Comment::all();

and pass this to view as

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

As it's collection you should use plural variable name to avoid confusion.

Now in your view you should use:

@if ($comments->count())
   @foreach ($comments as $comment)
      // here you display single comment data for example {{ $comment->text }}
   @endforeach
@endif
0
votes

Here you can do a few things:-

  1. You can downgrade your PHP version.
  2. You can update your syntax while executing the query:-

Change from this

$comment = Comment::get();

to this

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