FatalErrorException:在 non-object 上调用成员函数 count()

FatalErrorException: Call to a member function count() on a non-object

我正在尝试在 Laravel 5 中生成一个 unique/random 字符串并通过我的 table 检查它是否存在。

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

    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;
    }

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

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

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;
        }

您看到的错误告诉您您正在尝试对不是对象的值调用方法。很可能在您的代码中您 returning null 因为查询中的 where 没有 return 任何结果。您始终可以通过使用 dd():

查看 return 在 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))