【问题标题】:FatalErrorException: Call to a member function count() on a non-objectFatalErrorException:在非对象上调用成员函数 count()
【发布时间】:2015-06-14 13:01:17
【问题描述】:

我正在尝试在 Laravel 5 中生成一个唯一/随机字符串,并通过我的表检查它是否存在。

这就是我所拥有的,但它似乎给出了标题中所述的错误:

    public static function generate()
    {
        $exists = true;
        while ($exists) {
            $code = str_random(15);
            $check = self::where('code', $code)->first();
            if( ! $check->count()){
                $exists = false;
            }
        }
        return $code;
    }

有人知道为什么会出现这个错误吗?

【问题讨论】:

  • 错误是说它没有返回要调用的计数方法的对象。如果你运行self::where('code', $code)->first(),你会发现那里很可能什么都没有。试试if(!$check),而不是在上面调用count方法。
  • 谢谢,这修正了错误。
  • 太好了,如果你不介意我会抛出一个答案:)

标签: php database random laravel-5 unique


【解决方案1】:

您看到的错误是告诉您您正在尝试对一个不是对象的值调用方法。最有可能在您的代码中返回 null ,因为查询中的 where 没有返回任何结果。使用dd(),您可以随时查看在 Laravel 查询中返回的内容:

dd(Self::where('code', $code)->first())

因此,在调用 count() 或任何其他方法之前,您应该检查它是否不为空。

为此,您可以在您提供的代码中更新您的 if 语句:

public static function generate()
{
    $exists = true;

    while ($exists)
    {
        $code = str_random(15);

        // It's good practice to capitalise objects: Self instead of self
        $check = Self::where('code', $code)->first();

        if(!$check )
        {
            $exists = false;
        }
    }

    return $code;
}

正如 Halayem Anis 所提到的,您还可以使用 is_object() 函数测试您要检查的值是否是一个对象,但我认为您可能需要使用 && 运算符而不是 ||

if(!$check && !is_object($check))

【讨论】:

  • 接近 1k ... :) 继续前进
  • 哈哈,非常感谢我的朋友希望尽快加入 1k 俱乐部 :) - 顺便说一句,我完全不确定您是否需要使用 &&|| 如果您能澄清一下,将不胜感激
【解决方案2】:

在处理之前始终检查您的返回值...

public static function generate()
        {
            $exists = true;
            while ($exists) {
                $code = str_random(15);
                $check = self::where('code', $code)->first();
                if( is_null ($check) ||
                    ! is_object($check) ||
                    ! $check->count())
                {
                    $exists = false;
                }
            }
            return $code;
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-05
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    • 2013-11-29
    • 2010-09-26
    • 2012-04-20
    • 2015-05-01
    相关资源
    最近更新 更多