Last active
July 9, 2025 09:31
-
-
Save Maxiviper117/b478b8b0dd185d3aa61934b5d7731bb6 to your computer and use it in GitHub Desktop.
Laravel Artisan Command for creating Actions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// app/Console/Commmands/MakeActionCommand.php | |
namespace App\Console\Commands; | |
use Illuminate\Console\Command; | |
use Illuminate\Support\Facades\File; | |
use Illuminate\Support\Str; | |
class MakeActionCommand extends Command | |
{ | |
protected $signature = 'make:action {name : The name of the action class} {--db : Include a DB::transaction block}'; | |
protected $description = 'Create a new Action class'; | |
public function handle(): int | |
{ | |
$name = $this->argument('name'); | |
// Handle slashes/namespaces | |
$classPath = str_replace('\\', '/', $name); | |
$className = class_basename($name); | |
$namespacePart = Str::beforeLast(str_replace('/', '\\', $name), '\\'); | |
$namespace = $namespacePart ? "App\\Actions\\{$namespacePart}" : "App\\Actions"; | |
$directory = app_path('Actions/' . dirname($classPath)); | |
$filePath = "{$directory}/{$className}.php"; | |
if (File::exists($filePath)) { | |
$this->components->error("Action already exists at {$filePath}"); | |
return Command::FAILURE; | |
} | |
File::ensureDirectoryExists($directory); | |
File::put($filePath, $this->buildClass($namespace, $className)); | |
$this->components->info("Action [{$filePath}] created successfully."); | |
return Command::SUCCESS; | |
} | |
protected function buildClass(string $namespace, string $className): string | |
{ | |
$uses = ''; | |
$methodBody = "// TODO: Implement action logic for {$className}"; | |
if ($this->option('db')) { | |
$uses = "use Illuminate\\Support\\Facades\\DB;"; | |
$methodBody = <<<PHP | |
DB::transaction(function () { | |
// TODO: Implement transactional logic for {$className} | |
}); | |
PHP; | |
} | |
return <<<PHP | |
<?php | |
declare(strict_types=1); | |
namespace {$namespace}; | |
{$uses} | |
final class {$className} | |
{ | |
/** | |
* Execute the action. | |
*/ | |
public function handle(): void | |
{ | |
{$methodBody} | |
} | |
} | |
PHP; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment