laravelアプリケーションの新しい管理ユーザーの作成などのために、独自のartisanコマンドを作成する方法があります。
自作のartisanコマンドを作成すれば、管理ユーザーを作成したり、マイグレーションを実行したり、シーダーを実行したりと、プロジェクトのセットアップを行うことができるようになります。
この記事では、laravelプロジェクトで自作のartisanコンソールコマンドを作成する方法を紹介します。
この例では、新しい管理者ユーザーを作成するための自作のartisanコマンドを作成します。
この自作のaritisanコマンドは、名前、メールアドレス、パスワードを必要とします。
この例では、次のようなコマンドを作成します。
自作のartisanコマンド
php artisan admins:create
このコマンドで、新しいアドミンを作成します。そこで、まず以下のコマンドを実行し、コンソールクラスファイルを作成します。
php artisan make:console AdminCommand --command=admins:create
このコマンドの後、app/Console/Commands/ディレクトリにAdminCommand.phpというファイルがあるので、そのファイルを開いて、以下のコードを記述してください。
app/Console/Commands/AdminCommand.php
namespace App\Console\Commands; use Illuminate\Console\Command; use Hash; use DB; class AdminCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'admins:create'; /** * The console command description. * * @var string */ protected $description = 'Command description'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $input['name'] = $this->ask('What is your name?'); $input['email'] = $this->ask('What is your email?'); $input['password'] = $this->secret('What is the password?'); $input['password'] = Hash::make($input['password']); DB::table('admins')->insert($input); $this->info('Admin Create Successfully.'); } }
このコマンドクラスをKernel.phpファイルに登録する必要があるので、ファイルを開いてこのようにクラスを追加します。
app/Console/Kernel.php
namespace App\Console; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ Commands\AdminCommand::class, ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { } }
これで、自作のartisanコマンドを使う準備が整いました。
#artisanコマンドの確認 php artisan list #artisanコマンドの実行 php artisan admins:create
を実行してみてください。
自作のartisanコマンドの確認・実行ができる筈です。
この記事では、自作のartisanコマンドの作成方法を紹介しました。
参考になると幸いです。