function getXuid(Gamertag $gamertag, $attempts = 0)
{
    global $xboxapi;
    if (!empty($gamertag->xuid)) {
        return $gamertag->gamertag . ': ' . $xuid . PHP_EOL;
    }
    $xuid = 'failed to get xuid';
    $url = XboxAPI_URL . '/v2/xuid/' . rawurlencode($gamertag->gamertag);
    print $url . PHP_EOL;
    try {
        $response = $xboxapi->get($url, ['headers' => ['X-Auth' => XboxAPI_Key]]);
    } catch (Exception $e) {
        $message = $e->getMessage();
        print $message . PHP_EOL;
        if ($attempts < 2) {
            $attempts++;
            return getXuid($gamertag, $attempts);
        }
        if (strpos($message, '[status code] 404') === false) {
            die(PHP_EOL . PHP_EOL . $message . PHP_EOL);
        }
        $gamertag->error = $message;
        $gamertag->xuid = $xuid;
        $gamertag->save();
        print PHP_EOL;
        return false;
    }
    $xuid = $response->getBody();
    // store in the db
    $gamertag->xuid = $xuid;
    $gamertag->save();
    return 'XUID for ' . $gamertag->gamertag . ' = ' . $xuid . PHP_EOL;
}
<?php

date_default_timezone_set('Europe/London');
define('GAMERTAGS_CSV', 'gamertags.csv');
header('Content-Type: text/plain');
// get the composer autoloader
include __DIR__ . '/vendor/autoload.php';
if (!file_exists(GAMERTAGS_CSV)) {
    touch(GAMERTAGS_CSV);
    include __DIR__ . '/generate_gamertags.php';
    generate_gamertags();
}
// get our config file
include __DIR__ . '/config.php';
// load the helper files
include __DIR__ . '/helpers/database.php';
include __DIR__ . '/helpers/xboxapi.php';
$count = Gamertag::whereNull('xuid')->count();
while ($count > 0) {
    $gamertags = Gamertag::whereNull('xuid')->take(500)->get();
    foreach ($gamertags as $gamertag) {
        $gamertag = getXuid($gamertag);
        if ($gamertag !== false) {
            print $gamertag . PHP_EOL;
            $count--;
        }
    }
    $count = Gamertag::whereNull('xuid')->count();
}