Skip to content

Instantly share code, notes, and snippets.

@marcusmoore
Created November 10, 2014 04:36
Show Gist options
  • Save marcusmoore/3391b9cff585ac497bc4 to your computer and use it in GitHub Desktop.
Save marcusmoore/3391b9cff585ac497bc4 to your computer and use it in GitHub Desktop.
Backup folder to Dropbox with Flysystem within a Laravel command

This is an example of using a Laravel Command to sync files from the local filesystem to Dropbox. In my case it is the public/uploads directory that is being synced.

The creator of Flysystem, Frank de Jonge, gave me an example to work off of.

This example works because there are not many files in the uploads directory. I haven't tested it to see how it works with large files or large amount of files.

<?php
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Dropbox\Client;
use League\Flysystem\Filesystem;
use League\Flysystem\Adapter\Dropbox;
use League\Flysystem\Adapter\Local;
class UploadsBackupCommand extends Command {
protected $name = 'your:command-name';
protected $description = 'Backup uploads folder to Dropbox.';
# I should probably inject my dependencies here
public function __construct()
{
parent::__construct();
}
public function fire()
{
# Create dropbox client
$client = new Client(getenv("dropbox_token"), getenv("dropbox_project_name"));
# Create dropbox filesystem
$dropbox = new Filesystem(new Dropbox($client, "uploads"));
# Create local filesystem
$local = new Filesystem(new Local(public_path() . "/uploads"));
# Get contents from the uploads folder
$contents = $local->listContents("", true);
# I had problems with .DS_Store files so I filter them out here
$contents = array_filter($contents, function ($item)
{
if ( $item["basename"] !== ".DS_Store" )
{
return $item;
}
});
# If not already synced to dropbox, send it over
foreach ( $contents as $file )
{
if ( ! $dropbox->has($file["path"]) )
{
$dropbox->write($file["path"], $local->read($file["path"]));
}
}
}
protected function getArguments()
{
return [];
}
protected function getOptions()
{
return [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment