0

I create new own command in laravel, which updates some rows in mysql (in this case minecraft servers):

public function handle()
{
    $serversList = [
        'cubegame.pl',
        'dermc.pl',
        'feerko.pl',
        'skyup.pl',
        'mcosada.pl',
        'dragon-craft.pl',
        'gc2.pl'
    ];

    foreach ($serversList as $server) {
        $req = Http::get("https://api.mcsrvstat.us/2/$server");

        if($req->ok()) {
            $status = $req->json();

            echo( $status['motd']['html'][0] );

            // $serv = Server::updateOrCreate(
            //     [ 'name' => $server ],
            //     // [ 'name' => $server, 'ip' => $status['ip'] ],
            //     [
            //         'ip' => $status['ip'],
            //         'motd' => $status['motd']['html'][0] ?? null,
            //         'playersOnline' => $status['players']['online'] ?? null,
            //         'slots' => $status['players']['max'] ?? null,
            //         'version' => $status['version'] ?? null,
            //         'isOnline' => $status['online'],
            //         'icon' => $status['icon'],
            //     ]
            // );

        }
    }

    return 0;
}

When code was uncommented it throw error:

ErrorException Undefined index: motd.

Now, when in code is only echo it print variable $status['motd']['html'][0], but in next line it throws error

Undefined array key "motd"

Im so confused, please help.

Sorry for English :p

  • Link to api: https://api.mcsrvstat.us/ –  Jan 06 '21 at 18:06
  • What is `Http` class – RiggsFolly Jan 06 '21 at 18:17
  • @RiggsFolly it's a Laravel helper class. https://laravel.com/docs/8.x/http-client – miken32 Jan 06 '21 at 18:22
  • 1
    This might have to do with the fact that some servers do not have an motd set. For example `dermc.pl` does not have that information. You can also visit those routes in your browser to see the json response. – Remy Jan 06 '21 at 18:22
  • You have the right idea in trying to use the null coalesce operator, but it only applies to the last element (in this case the `[0]`) so instead you'll need to use a more traditional check like `'motd' => array_key_exists('motd', $status) ? $status['motd']['html'][0] ?? null : null,` – miken32 Jan 06 '21 at 18:24
  • Of course if there is a chance `$status['motd']` is defined, but `$status['motd']['html']` is not, further checking would be necessary. Seems odd that the API would not have consistent responses. – miken32 Jan 06 '21 at 18:30
  • But in database all servers (where I add "?? null" ) have this field as null –  Jan 06 '21 at 18:32
  • Motd, playersOnline, playersMax and version are null to all servers –  Jan 06 '21 at 18:33
  • In example: https://api.mcsrvstat.us/2/cubegame.pl have an ip, motd, version but in database this values are null –  Jan 06 '21 at 18:37

0 Answers0