Hello Devs,
In this tutorial, we will learn Laravel 8 Custom Command Example Tutorial
If we want to create a custom command then we can easily make a project setup like create one admin user, run migration, run seeder and etc.
Follow this step-by-step guide below.
Custom command
php artisan users:create
fire below command and create console class file.
php artisan make:command UserCommand --command=users:create
app/Console/Commands/UserCommand.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\User;
use Hash;
class UserCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'users: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 int
*/
public function handle()
{
$input['name'] = $this->ask('Your name?');
$input['email'] = $this->ask('Your email?');
$input['password'] = $this->secret('What is the password?');
$input['password'] = Hash::make($input['password']);
User::create($input);
$this->info('User Create Successfully.');
}
}
register this command class in Kernel.php file
<?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\UserCommand::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
}
}
Now run below command:
php artisan list
php artisan users:create
May this example help you.