You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.4部署Heroku用SQS队列时持续发空消息并报Countable错误

解决Laravel 5.4 + Heroku SQS队列的count()错误问题

Hey there, let's break down this frustrating count() error you're hitting with your Laravel 5.4 app on Heroku using SQS. I've seen this exact issue crop up when PHP versions get bumped beyond what Laravel 5.4 was built to support. Here's how to fix it step by step:

1. 先锁定PHP版本(核心原因)

Laravel 5.4 officially supports PHP 5.6 to 7.1, but Heroku might have auto-upgraded your environment to PHP 7.2+. In PHP 7.2+, calling count() on non-array/non-Countable objects throws that exact ErrorException you're seeing.

First, check your current PHP version on Heroku:

heroku run php -v

If it's 7.2+, add a PHP version constraint to your composer.json to force Heroku to use a compatible version:

"require": {
    "php": ">=5.6.4 <7.2",
    // 其他依赖项保持不变
}

Commit and deploy the change:

git add composer.json
git commit -m "Lock PHP version to <7.2 for Laravel 5.4 compatibility"
git push heroku master

2. 升级Laravel 5.4到最新补丁版本

The final patch releases of Laravel 5.4 (v5.4.36 and above) fixed some PHP 7.2 compatibility bugs. Run this to upgrade:

composer update laravel/framework --with-dependencies

Note: Laravel 5.4 is no longer maintained, so this won't add security patches, but it will resolve the count() error.

3. 排查自定义队列任务代码

If the error persists after the above steps, check your own queue job code for instances where you're calling count() on non-Countable objects (like null, stdClass, or uninitialized variables). For example:

// ❌ Bad: Calling count() on a potentially non-countable variable
$data = $this->fetchSomeData();
if (count($data) > 0) {
    // ...
}

Fix it by adding a check first:

// ✅ Good: Verify it's countable before using count()
$data = $this->fetchSomeData();
if ((is_array($data) || $data instanceof Countable) && count($data) > 0) {
    // ...
}
// Or use empty() for simpler cases
if (!empty($data)) {
    // ...
}

4. 临时应急:手动修复框架核心文件(不推荐长期使用)

If you can't upgrade the framework right now, you can manually patch the Laravel core file that's triggering the error (usually Illuminate/Queue/Worker.php). Look for lines using count() on variables that might not be countable, and add a check:

// Before
if (count($this->options['delay']) > 0) { ... }

// After
if (isset($this->options['delay']) && (is_array($this->options['delay']) || $this->options['delay'] instanceof Countable) && count($this->options['delay']) > 0) { ... }

Warning: This change will get overwritten if you run composer update later, so only use it as a temporary fix.

After making your fixes, restart the Heroku worker process to apply changes:

heroku ps:restart worker

内容的提问来源于stack exchange,提问作者bdweix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:13:37