Home » Php » php – Call to a member function count() on a non-object (Laravel 5)

php – Call to a member function count() on a non-object (Laravel 5)

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have a list of projects, where I can click on and it (needs to) show the project name, and the list of the projects’ tasks (ToDo application)

But when I click on a certain project I get this error.

(The “H2” project name will show up)

h2>{{{ $project->name }}}</h2>

@if ( !$project->tasks->count())
    There are no tasks for this project.
@else
    <ul>
        @foreach( $project->tasks as $task)
            <li><a href="{{ route('projects.tasks.show', [$project->slug, $task->slug]) }}">{{ $task->name }}</a></li>
        @endforeach
    </ul>
@endif
How to&Answers:

$project->tasks is an array and you cant call count() on the array. So try with –

count($project->tasks)

Answer:

Try count($project->tasks)==0

h2>{{{ $project->name }}}</h2>

@if ( count($project->tasks)==0)
    There are no tasks for this project.
@else
    <ul>
        @foreach( $project->tasks as $task)
            <li><a href="{{ route('projects.tasks.show', [$project->slug, $task->slug]) }}">{{ $task->name }}</a></li>
        @endforeach
    </ul>
@endif

Answer:

I see your issue is resolved but this might help someone else 😀

The following piece of code might work for you, but it’s not that we can’t call count() on the array.

count($project->tasks)

Instead of this

h2>{{{ $project->name }}}</h2>

@if ( !$project->tasks->count()) // tasks is plural -> wrong.
    There are no tasks for this project.
@else
    <ul>
        @foreach( $project->tasks as $task) // here too!
            <li><a href="{{ route('projects.tasks.show', [$project->slug, $task->slug]) }}">{{ $task->name }}</a></li>
        @endforeach
    </ul>
@endif

Try doing this

h2>{{{ $project->name }}}</h2>

@if ( !$project->task->count())
    There are no tasks for this project.
@else
    <ul>
        @foreach( $project->task as $task)
            <li><a href="{{ route('projects.tasks.show', [$project->slug, $task->slug]) }}">{{ $task->name }}</a></li>
        @endforeach
    </ul>
@endif