각 테이블에 대해 모델, 리포지토리, 서비스, 컨트롤러를 자동으로 생성하는 Laravel Artisan 명령 만들기

발행: (2025년 12월 5일 오후 12:15 GMT+9)
3 min read
원문: Dev.to

Source: Dev.to

맞춤 Artisan 명령어: 레이어 자동 생성

실행:

php artisan make:command GenerateCrudFromDb

명령어 구현

Replace the file app/Console/Commands/GenerateCrudFromDb.php with:

option('table');

        if (empty($tables)) {
            // If no table specified, get all tables
            $tables = $this->getAllTables();
        }

        foreach ($tables as $table) {
            $this->generateForTable($table);
        }

        $this->info('All CRUD layers generated successfully!');
    }

    protected function getAllTables()
    {
        $database = DB::getDatabaseName();
        $tables = DB::select("SHOW TABLES");
        $tables = array_map(function ($table) use ($database) {
            return $table->{'Tables_in_' . $database};
        }, $tables);
        return $tables;
    }

    protected function generateForTable($table)
    {
        $className = Str::studly(Str::singular($table));
        $modelName = $className;
        $controllerName = $className . 'Controller';
        $repositoryName = $className . 'Repository';
        $serviceName = $className . 'Service';

        $columns = $this->getTableColumns($table);

        $this->createModel($modelName, $columns);
        $this->createRepository($repositoryName, $modelName);
        $this->createService($serviceName, $repositoryName);
        $this->createController($controllerName, $serviceName);

        $this->info("CRUD generated for table: {$table}");
    }

    protected function getTableColumns($table)
    {
        $columns = DB::select("SHOW COLUMNS FROM {$table}");
        $fillable = [];
        foreach ($columns as $column) {
            if (!in_array($column->Field, ['id', 'created_at', 'updated_at', 'deleted_at'])) {
                $fillable[] = $column->Field;
            }
        }
        return $fillable;
    }

    protected function createModel($name, $fillable)
    {
        $modelPath = app_path("Models/{$name}.php");
        if (!File::exists($modelPath)) {
            $fillableArray = implode("','", $fillable);
            $content = "info("Model created: {$name}");
        }
    }

    protected function createRepository($name, $model)
    {
        $repoPath = app_path("Repositories/{$name}.php");
        if (!File::exists($repoPath)) {
            $content = "{$model} = \${$model};
    }

    public function all() { return \$this->{$model}::all(); }
    public function find(\$id) { return \$this->{$model}::find(\$id); }
    public function create(array \$data) { return \$this->{$model}::create(\$data); }
    public function update(\$id, array \$data) { 
        \$record = \$this->find(\$id); 
        if(\$record) \$record->update(\$data); 
        return \$record; 
    }
    public function delete(\$id) { 
        \$record = \$this->find(\$id); 
        if(\$record) \$record->delete(); 
        return \$record; 
    }
}
";
            File::put($repoPath, $content);
            $this->info("Repository created: {$name}");
        }
    }

    protected function createService($name, $repository)
    {
        $servicePath = app_path("Services/{$name}.php");
        if (!File::exists($servicePath)) {
            $content = "{$repository} = \${$repository};
    }

    public function all() { return \$this->{$repository}->all(); }
    public function find(\$id) { return \$this->{$repository}->find(\$id); }
    public function create(array \$data) { return \$this->{$repository}->create(\$data); }
    public function update(\$id, array \$data) { return \$this->{$repository}->update(\$id, \$data); }
    public function delete(\$id) { return \$this->{$repository}->delete(\$id); }
}
";
            File::put($servicePath, $content);
            $this->info("Service created: {$name}");
        }
    }

    protected function createController($name, $service)
    {
        $controllerPath = app_path("Http/Controllers/{$name}.php");
        if (!File::exists($controllerPath)) {
            $content = "{$service} = \${$service};
    }

    public function index() { return \$this->{$service}->all(); }
    public function store(Request \$request) { return \$this->{$service}->create(\$request->all()); }
    public function show(\$id) { return \$this->{$service}->find(\$id); }
    public function update(Request \$request, \$id) { return \$this->{$service}->update(\$id, \$request->all()); }
    public function destroy(\$id) { return \$this->{$service}->delete(\$id); }
}
";
            File::put($controllerPath, $content);
            $this->info("Controller created: {$name}");
        }
    }
}

디렉터리 설정

Laravel 프로젝트에 다음 디렉터리가 존재하는지 확인하세요:

  • app/Models
  • app/Repositories
  • app/Services
  • app/Http/Controllers

사용법

데이터베이스의 모든 테이블에 대해 생성

php artisan generate:crud

특정 테이블에 대해 생성

php artisan generate:crud --table=customers --table=orders

이 명령은 자동으로 다음을 생성합니다:

  • Models: 테이블 컬럼에서 $fillable을 채워 생성
  • Repositories: 기본 CRUD 작업을 구현
  • Services: 리포지토리에게 위임
  • Controllers: 표준 RESTful 액션을 노출

모든 레이어는 Repository‑Service 패턴을 따릅니다.

Back to Blog

관련 글

더 보기 »

🧱 강의 9B : 제품 관리 (Angular)

소개 이 모듈은 전체 제품 관리 기능을 구축하는 데 중점을 두며, 전체 CRUD 작업과 프론트엔드와의 원활한 통합을 포함합니다.