如果查询结果为空,则不会在 lumen 中执行下一条语句

If query result is null it didnt execute next statements in lumen

$user = User:: select('name', 'email_id', 'gender')
              ->where($field, "=", $postData['login'])
                ->where("password", "=", sha1($postData['password']))
                ->first();

        if ($user) {
            $token=str_random(60);
            $user->api_token=$token;
            $user->save();

            $response['status'] = 200;
            $response['message'] = "success";
            $response['data'] = $user;
        }
        else {
            $response['status'] = 200;
            $response['message'] = "failure";
        }

在这段代码中,"if" 语句只 运行 如果 $user 有一些值,这是显而易见的,但如果 $user 为空,则下一个语句不会执行。

即使我在查询下面写了 echo "anything",它也没有显示,它只是 return null。所以我没有在其他块中写入值。

我尝试过不同的方法,但都失败了。

如果没有符合给定条件的用户,查询可能会抛出 "ModelNotFoundException",您可以尝试捕获异常并查看是否是这种情况吗?

try {
$user = User:: select('name', 'email_id', 'gender')
          ->where($field, "=", $postData['login'])
            ->where("password", "=", sha1($postData['password']))
            ->first();
} catch (Illuminate\Database\Eloquent\ModelNotFoundException e) {
    dd(e);
}