Ashley Wrench
Ashley Wrench

Reputation: 990

Array is empty, but it keeps thinking there somthing inside

$result = usr::where("username", $username)->where("password", sha1($password))->get();

    echo $result;


    if(!empty($result)){
        echo " -WORKED :D";
    }else{ echo "FAILED D:"; }

Outcome is always '[] - WORKED :D' , the database isnt retruning anything, and the array is clearly empty, why is it thinking that theres something inside of the array?

EDIT:

OK, so I found a fix relatively quick, and I'm not sure why this works, but empty() dose not.

I just used if(count($results) < 1){ and it worked fine, can anyone explain why it wasn't working with the empty() condition?

Upvotes: 2

Views: 112

Answers (2)

darthmaim
darthmaim

Reputation: 5148

get() returns a Laravel Collection (Illuminate\Database\Eloquent\Collection), not an array. You can check if its empty with $result->isEmpty() or with $result->count() > 0.

You can also use $result->toArray() to convert the collection into a normal php array.

Upvotes: 1

Blaatpraat
Blaatpraat

Reputation: 2849

Because it is not empty, you get a collection which is not filled with data.
Because a collection is a custom object, PHP does not know that it can be empty.

You need the isEmpty method from the Laravel framework.

Code line would be:

if(!$result->isEmpty())

Upvotes: 6

Related Questions