Search code examples
phpdatabaserandomlaravel-5unique

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


I'm trying to generate a unique/random string in Laravel 5 and check it through my table to see if it exists.

This is what I have, but it seems to be giving the error stated in the title:

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

Anyone know why it's giving this error?


Solution

  • The error you're seeing is telling you that you're trying to call a method on a value which is not an object. Most likely in your code you're returning null as the where in your query didn't return anything results. You can always see what you're returning in Laravel queries by using dd():

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

    So before calling count() or any other method on a value for which you're expecting an object you should check it's not null.

    Do to this you can update your if statement in the code you provided:

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

    As mentioned by Halayem Anis you can also test if the value you're checking is an object using the is_object() function, but I think you may need to use the && operator instead of ||:

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