Laravel Advance | Laravel Create Custom Artisan Command with Example

Raviya Technical
2 min readNov 6, 2021

It’s better if we make our own artisan command for like project setup, create a new admin user, etc in our laravel application. If we create a custom command then we can make a project setup like create one admin user, run migration, run seeder and etc. In this post, I give you an example, how to create console commands in the laravel project.

This example will create a custom command to create a new admin user. This custom command will ask your name, email, and password. In this example, we will create commands like

Custom command

php artisan admins:create

This command through we will create new admins. So first fire below command and create a console class file.

php artisan make:console AdminCommand --command=admins:create

After this command, you can find one file AdminCommand class in the console directory. so one that files and put bellow code.

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.');}}

Ok, now we need to register this command class in the Kernel.php file, so open the file and add class this way

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){}}

Now we are ready to use or a custom command, you fire the below command and check you can find the command in the list this way “admins:create”.

php artisan list
php artisan admins:create

--

--