10-Apr-2023
.
Admin
Hi Guys,
Today, I will learn you how to create a custom command in laravel 9. We will show an example of laravel 9 custom command. I make our own artisan command for like project setup, create new admin user etc in our laravel 9 application. If I 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, we give you an example, of how to create console commands in the laravel 9 project.
In this example, I will create a custom command to create a new admin user. This custom command will ask for your name, email, and password.
Step 1: Download Laravel
Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip the following step.
composer create-project laravel/laravel example-app
Step 2: Add Custom command
php artisan users:create
This command through we will create new admins. So first fire the bellow command and create a console class file.
php artisan make:command UserCommand --command=users:create
Next to this command you can find one file UserCommand class in the console directory. so one that file and put bellow code.
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.');
}
}
After, Now I need to register this command class in Kernel.php file, so open file and add class this way:
Kernel.php
<?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 we are ready to use a custom command, you fire the below command and check if you can find the command in the list this way "users:create".
php artisan list
php artisan users:create
It Will help you...
#Laravel 9