Laravel

Database Refresh Command 💡

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Storage;

class RefreshDatabase extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'database:refresh {--sql=database/base_backup/backup.sql : Path to the SQL file}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Drops the old database, creates a new one, imports an SQL file, and runs migrations';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $database = env('DB_DATABASE');

        $this->info('Dropping the old database...');

        DB::statement("DROP DATABASE IF EXISTS `$database`");

        $this->info('Creating a new database...');

        DB::statement("CREATE DATABASE `$database`");

        config(['database.connections.mysql.database' => $database]);

        DB::reconnect();

        $sqlFilePath = $this->option('sql');

        if ($sqlFilePath && file_exists(base_path($sqlFilePath))) {
            $this->info('Importing the SQL file...');
            $sql = file_get_contents(base_path($sqlFilePath));
            DB::unprepared($sql);
        } else {
            $this->warn('SQL file not found or not specified. Skipping SQL import.');
        }

        $this->info('Running migrations...');
        
        Artisan::call('migrate', ['--force' => true]);

        $this->info('Database refresh complete.');

        return 0;
    }
}