Laravel Create Custom Artisan Command with Example

https://www.itsolutionstuff.com/post/laravel-5-create-custom-artisan-command-with-exampleexample.html

Laravel Create Custom Artisan Command with Example

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

Custom command

php artisan admins:create

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

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

After this command you can find one file AdminCommand class in console directory. so one that file 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 Kernel.php file, so open 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 custom command, you fire bellow command and check you can find command in the list this way "admins:create".

Read Also: Laravel - How to create custom error page with example

php artisan listphp artisan admins:create

you can checkkk....

Last updated