LARAVEL

Laraveldə verilənlə bazasının ehtiyat nüsxəsini almaq

10.07.2024 2 dəq oxuma
<?php

namespace App\Console\Commands;

use App\Mail\ContactEmail;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Mail;

class BackupDatabase extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'db:backup';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Backup the MySQL database using mysqldump';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        $dbHost = config('database.connections.mysql.host');
        $dbName = config('database.connections.mysql.database');
        $dbUser = config('database.connections.mysql.username');
        $dbPass = config('database.connections.mysql.password');
        $dbPort = config('database.connections.mysql.port');

        // Define the backup file path and name
        $dir = 'backups/' . date('Y') . '/' . date('m') . '/' . date('d') . '/';
        $directory = public_path($dir);
        $fileName = Carbon::now()->format('H-i-s') . '.sql';
        $filePath = $directory . '/' . $fileName;

        // Create the backups directory if it doesn't exist
        if (!File::exists($directory)) {
            File::makeDirectory($directory, 0755, true);
        }

        $command = sprintf(
            'mysqldump --user=%s --password=%s --host=%s --port=%s %s > %s',
            escapeshellarg($dbUser),
            escapeshellarg($dbPass),
            escapeshellarg($dbHost),
            escapeshellarg($dbPort),
            escapeshellarg($dbName),
            escapeshellarg($filePath)
        );

        $output = null;
        $returnVar = null;
        exec($command, $output, $returnVar);

        if ($returnVar !== 0) {
            $this->error('Failed to backup the database');
        } else {
            $details = [
                'title' => date('Y-m-d H:i:s') . ' tarixində ehtiyat nüsxə uğurla alındı və yükləmək üçün aşağıdakı linkə klikləyin.',
                'link' => asset($dir . $fileName)
            ];

            Mail::to('rahim.suleymanov94@gmail.com')->send(new ContactEmail($details));
            $this->info('Database backup was successful');
        }
    }
}

 

Digər dildə: EN