Laravel5.2のプロジェクトで日次のバッチ処理追加を依頼されたため、環境を立ててartisanコマンドを実行したところ
[ErrorException]
count(): Parameter must be an array or an object that implements Countable
というエラーが発生した。
artisan コマンドに -v オプションつけて叩いたところ、Illuminate/Database/Eloquent/Builder.phpでエラーが起きてるよ、と言っている。該当箇所は下記。
/**
* Apply the given scope on the current builder instance.
*
* @param callable $scope
* @param array $parameters
* @return mixed
*/
protected function callScope(callable $scope, $parameters = [])
{
array_unshift($parameters, $this);
$query = $this->getQuery();
// We will keep track of how many wheres are on the query before running the
// scope so that we can properly group the added scope constraints in the
// query as their own isolated nested where statement and avoid issues.
$originalWhereCount = count($query->wheres);
$result = call_user_func_array($scope, $parameters) ?: $this;
if ($this->shouldNestWheresForScope($query, $originalWhereCount)) {
$this->nestWheresForScope($query, $originalWhereCount);
}
return $result;
}
エラーメッセージでググったところ、PHP7.2からcount()にnull渡すとwarning吐くようになったらしい。
もともと、nginx経由の場合は7.0に振るよう、nginx.confを書き換えて凌いでおいたのだが、CLIだとデフォルトバージョンの7.2の方が呼ばれてしまっている、ということらしい。確認すると、確かにartisanコマンド実行時には7.2になっている。
$ php artisan tinker
Psy Shell v0.7.2 (PHP 7.2.3-1+ubuntu16.04.1+deb.sury.org+1 ― cli) by Justin Hileman
CLIのデフォルトバージョンを変えてしまえ、ということで方法を調べたところ、だいたい同じ問題で困っている人を発見。
https://stackoverflow.com/questions/48813252/calling-composer-with-specific-php-version-on-homestead
回答中に、下記githubへのリンクがあった。
https://github.com/laravel/homestead/blob/master/resources/aliases
開発環境用の応急処置なので、シェルの内容のうち、下記必要な3行だけ実行して解決。
sudo update-alternatives --set php /usr/bin/php7.0
sudo update-alternatives --set php-config /usr/bin/php-config7.0
sudo update-alternatives --set phpize /usr/bin/phpize7.0
$ php artisan tinker
Psy Shell v0.7.2 (PHP 7.0.28-1+ubuntu16.04.1+deb.sury.org+1 ― cli) by Justin Hileman
無事、7.0.28になりました。
本番のミドルウェアバージョンしっかり確認してから環境構築すればよかった。
参考
PHP7.2のcountにハマった話
https://qiita.com/masaki-ogawa/items/1671d110b2286ececd09
下位互換性のない変更点(PHPドキュメント)
http://php.net/manual/ja/migration72.incompatible.php
追記(2020-04-08)
homestead 6以降であれば、コマンドが用意されている。
https://readouble.com/laravel/6.x/ja/homestead.html#multiple-php-versions