调用非对象上的成员函数count()(Laravel 5)

时间:2015-04-29 11:00:59

标签: php laravel

我有一个项目列表,我可以点击它,它(需要)显示项目名称和项目任务列表(ToDo应用程序)

但是当我点击某个项目时,我收到了这个错误。

(“H2”项目名称将显示)

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

3 个答案:

答案 0 :(得分:6)

$project->tasks是一个数组,你不能在数组上调用count()。所以试试 -

count($project->tasks)

答案 1 :(得分:0)

尝试计数($ project-&gt; 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

答案 2 :(得分:0)

我看到您的问题已解决,但这可能会对其他人有所帮助:D

以下代码段可能对您有用,但这并不是我们不能在数组上调用count()。

count($project->tasks)

代替这个

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

尝试这样做

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