【问题标题】:Solve issue of upgrading to php 7.2 in laravel 5.4 application解决 laravel 5.4 应用升级到 php 7.2 的问题
【发布时间】:2018-05-29 08:44:35
【问题描述】:

本周我已将我的 laravel 应用程序 php 版本升级到 php 7.2,从那时起,我的 laravel 应用程序将面临大问题。在将 php 升级到 7.2 之前,一切正常。

主要问题是关于抛出此错误的 count()array_merge() 函数:

array_merge()函数代码如下:

$array = array_merge(
                $model->toSearchableArray(), $model->scoutMetadata()
            );

            if (empty($array)) {
                return;
            }

ErrorException · array_merge(): 参数 #1 不是数组。

当模型不返回任何记录并返回 null 时,例如在此代码中,我将面临 count() 错误:

count(TutorialReview::where('TutorialID', 5)->where('UserID', 6)->get())

count(): 参数必须是数组或者实现了Countable的对象。

我的 laravel 版本是 5.4

现在我的问题是如何解决这些问题,升级到 laravel 5.5 是否可以解决任何问题?

【问题讨论】:

  • 使用 @ 忽略我认为的警告。

标签: php laravel laravel-5.4 laravel-5.5


【解决方案1】:

PHP 7.2 中更改了以下 RFC 中的 count() 行为:https://wiki.php.net/rfc/counting_non_countables

但是你可以在 laravel 中使用->count() 来获取计数,这是一个例子:

$count = TutorialReview::where('TutorialID', 5)->where('UserID', 6)->get()->count();

这样您可以获得总记录数。

【讨论】:

  • 谢谢,这似乎是计数问题的解决方案。我的问题是因为每次在 get() 函数之后我使用 ->first() 并且在 count() 函数中都会给出错误。
  • @atiehmokhtary,如果这是您问题的解决方案,您可以接受作为答案。提前致谢
【解决方案2】:

只需在count 之前添加@。即。

@count(object or array);

【讨论】:

  • 这个解决方案效果很好!但我需要进一步解释为什么我需要添加 @ 符号。
  • @ad3bay0 @ 符号抑制给定函数调用的错误
  • 没有解决根本问题,只是告诉错误保持安静
【解决方案3】:

要解决 array_merge() 问题,请尝试以下步骤:

  1. 带有数据的 app/config 中的 sluggable.php 配置文件

    return ['source' => null, 'maxLength' => null, 'method' => null, 'separator' => '-', 'unique' => true, 'uniqueSuffix' => null, 'includeTrashed' => false, 'reserved' => null, 'onUpdate' => false, ];

  2. 执行命令,php artisan config:cache

解决 count() 问题Try This

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

实际上这不是错误,而是预期的行为。 Laravel 5.4 或 5.5 与 Php 7.2 不完全兼容。 Count() 行为在 PHP 7.2 中发生了变化 Look at this

在兼容性问题修复之前,只需使用 PHP 7.1 或更低版本。

【讨论】:

  • 感谢回复,我找不到 sluggable.php 文件,请您解释一下解决 array_merge() 问题的更多信息吗?
【解决方案4】:

试试这个:

$array = array_merge(
    collect($model->toSearchableArray())->toArray(), $model->scoutMetadata()
);

在计算模型实例时,也可以通过 ->count() 而不是 count() 执行此操作

【讨论】:

    【解决方案5】:

    只需在 web.php 中添加以下代码

    if (version_compare(PHP_VERSION, '7.2.0', '>=')) {
        // Ignores notices and reports all other kinds... and warnings
        error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);
        // error_reporting(E_ALL ^ E_WARNING); // Maybe this is enough
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-13
      • 2014-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多