DragonFire
DragonFire

Reputation: 4082

Laravel Query Inside Json Loop

Querying inside a json loop always returns exists even when row does not exist.

Hi I have a Json Object which looks like this

{"+888588888":"Person 1", "[email protected]":"Person 2"}

I am using the following code to check whether the record exists in the table:

    // Get The Json From Source
    $json = json_decode($request->getContent(), true);

    // Loop Through Json And Insert Into Mysql
    foreach ($json as $key => $value) {

        $result = UserInvitesModel::where('mysql_user_id', $mysql_user_id)
            ->where(function ($q) use ($key, $value) {
                $q->where('phone', $key)
                    ->orWhere('email', $key);
            })->get();

        if (empty($result)) {
            echo "does-not-exist ";
        } else {
            echo "exists ";
        }
    }

I am always getting exists

Upvotes: 0

Views: 150

Answers (2)

N69S
N69S

Reputation: 17206

$result is never "empty"!! even if no record is returned, it still is an instance of a Collection::class with empty array as items.

You should test on $result->count() (a method of the collection class)

or improve your code.

foreach ($json as $key => $value) {
    $count = UserInvitesModel::where('mysql_user_id', $mysql_user_id)
        ->where(function ($q) use ($key, $value) {
            $q->where('phone', $key)
                ->orWhere('email', $key);
        })->count(); //return an integer

    if (!$count) {
        echo "does-not-exist ";
    } else {
        echo "exists ";
    }
}

if you need the user entity use first instead

foreach ($json as $key => $value) {
    $user = UserInvitesModel::where('mysql_user_id', $mysql_user_id)
        ->where(function ($q) use ($key, $value) {
            $q->where('phone', $key)
                ->orWhere('email', $key);
        })->first(); //returns null or an instance of the model

    if (!$user) {
        echo "does-not-exist ";
    } else {
        echo "exists ";
    }
}

Upvotes: 1

Anthony Aslangul
Anthony Aslangul

Reputation: 3847

You are using empty() on a Collection and that's the problem.

The ->get() method you use returns a Collection and in order to check if it has at least one element, you have to use isEmpty():

// Get The Json From Source
    $json = json_decode($request->getContent(), true);

    // Loop Through Json And Insert Into Mysql
    foreach ($json as $key => $value) {

        $result = UserInvitesModel::where('mysql_user_id', $mysql_user_id)
            ->where(function ($q) use ($key, $value) {
                $q->where('phone', $key)
                    ->orWhere('email', $key);
            })->get();

        if ($result->isEmpty()) {
            echo "does-not-exist ";
        } else {
            echo "exists ";
        }
    }

empty() always returns false on Collection:

empty(collect()); // false
collect()->isEmpty(); //true

Upvotes: 1

Related Questions