Skip to content

Instantly share code, notes, and snippets.

@krisanalfa
Last active September 25, 2023 17:25
Show Gist options
  • Save krisanalfa/0407dd822f2888226f45 to your computer and use it in GitHub Desktop.
Save krisanalfa/0407dd822f2888226f45 to your computer and use it in GitHub Desktop.
Lumen Key Generator Commands
<?php
namespace App\Console\Commands;
use Illuminate\Support\Str;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
class KeyGenerateCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'key:generate';
/**
* The console command description.
*
* @var string
*/
protected $description = "Set the application key";
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
$key = $this->getRandomKey();
if ($this->option('show')) {
return $this->line('<comment>'.$key.'</comment>');
}
$path = base_path('.env');
if (file_exists($path)) {
file_put_contents(
$path,
str_replace(env('APP_KEY'), $key, file_get_contents($path))
);
}
$this->info("Application key [$key] set successfully.");
}
/**
* Generate a random key for the application.
*
* @return string
*/
protected function getRandomKey()
{
return Str::random(32);
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return array(
array('show', null, InputOption::VALUE_NONE, 'Simply display the key instead of modifying files.'),
);
}
}
@jagadishnallappa
Copy link

I think you should change from fire to handle function. Because Abstract class Command has execute method will detect handle or __invoke. For anyone face issue
Method App\Console\Commands\KeyGenerateCommand::__invoke() does not exist

Just change fire to handle will resolve the problem. Hope this help

Aye. I confirm that he is right. This solves Method App\Console\Commands\KeyGenerateCommand::__invoke() does not exist.

@Kane-R-G
Copy link

Kane-R-G commented Feb 22, 2022

@frama21 Your solution works well but I had to update this section:

if ($this->option('show')) {
    return $this->line('<comment>' . $key . '</comment>');
 }

to

if ($this->option('show')) {
    $this->line('<comment>' . $key . '</comment>');
 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment