Skip to content

Instantly share code, notes, and snippets.

@kyawkyawsoezhu
Created July 17, 2021 08:14
Show Gist options
  • Save kyawkyawsoezhu/399e54286783a40074f3ea0d30a6e4de to your computer and use it in GitHub Desktop.
Save kyawkyawsoezhu/399e54286783a40074f3ea0d30a6e4de to your computer and use it in GitHub Desktop.
Laravel artisan command for deploy to the destination server
DEPLOY_USER=awesomeuser
DEPLOY_SERVER=awesome-api.example.com
DEPLOY_PATH=/var/www/awesome-api
APP_NAME=AwesomeAPI
APP_ENV=production
# and the rest of your env file for production
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
class Deploy extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'deploy';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Deploy code to production';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
if (!File::exists(".env.deploy")) {
$this->error("can't file .env.deploy file");
return 1;
}
if (!File::exists(".env.production")) {
$this->error("need .env.production file");
return 1;
}
$deployConfig = (new \josegonzalez\Dotenv\Loader(base_path('.env.deploy')))->parse()->toArray();
$deployUser = $deployConfig['DEPLOY_USER'];
$deployServer = $deployConfig['DEPLOY_SERVER'];
$deployPath = $deployConfig['DEPLOY_PATH'];
$deployDestination = "{$deployUser}@{$deployServer}:{$deployPath}";
$this->info("Update main repository on github is deploying to {$deployDestination}");
exec("ssh -p22 {$deployUser}@{$deployServer} ' cd {$deployPath}; {$this->deployCommands()} ' ", $deployOutput);
$this->info(implode("\n", $deployOutput));
if ($this->confirm("Want update prduction '.env'?")) {
$this->info("Replacing .env.production from local to .env on the destination server.");
exec("scp -r .env.production {$deployDestination}/.env", $envReplaceOutput);
$this->info(implode("\n", $envReplaceOutput));
$this->info('Replace env file finish.');
}
$this->info("Deploy complete.");
return 0;
}
private function deployCommands()
{
return '
git pull origin main
composer install --no-dev --optimize-autoloader
php artisan config:cache
php artisan migrate --force
php artisan queue:restart
';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment