Use the DigitalOcean API with Laravel

DigitalOcean uses a great API you can use to create, delete or do basically everything you want with your Droplets. Fortunately there's a Laravel package that makes it even easier to use the API.

How to install the DigitalOcean package in Laravel

You can easily install the package by running composer require graham-campbell/digitalocean.

Then you have to include it in config/app.php file by adding the following two lines:

GrahamCampbell\DigitalOcean\DigitalOceanServiceProvider::class, to providers.

'DigitalOcean' => GrahamCampbell\DigitalOcean\Facades\DigitalOcean::class, to aliases.

Now you're ready to go and you can use the DigitalOcean API inside your app.

How to use the DigitalOcean API with Laravel

Personally I've created some helpers and created a helper file to make it easier to use it.

Below you can find some examples on how to create and destroy your droplets.

static function createDroplets($count = 1, $name, $location = 'nyc3', $size = '512mb', $image = '', $backups = false, $ipv6 = false, $privateNetworking = false, $userData = '')
{
	for($i = 1; $i <= $count; $i++)
	{
		$names[] = $name;
	}

	$droplets = DigitalOcean::droplet()->create($names, $location, $size, $image, $backups, $ipv6, $privateNetworking, Config::get('DOKey'), $userData);

	foreach($droplets as $droplet)
	{
		$IDs[] = $droplet->id;
	}

	return $IDs;
}

Please note that I'm using a custom config file in config/custom.php where I have the DigitalOcean API key.

The function below is used to delete all droplets with a specific name:

static function deleteAllDroplets($name)
{
	$droplets = DigitalOcean::droplet()->getAll();

	foreach($droplets as $droplet)
	{
		if($droplet->name == $name)
		{
			DigitalOcean::droplet()->delete($droplet->id);
		}
	}
}

There's a lot more to be done with the DigitalOcean API, but maybe in a future post.