Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
In this tutorial, I will give you an example of the “How to Create Custom Artisan command in Laravel“, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application.
First, what we’re doing here, This is the example :
Sometimes we need to create an artisan command in the Laravel application for performing tasks and advanced customization on applications, like changing in migration, Cron jobs, Scheduler on a local and live server.
We just follow these steps to create a simple command to know our Database name using the artisan commands.
php artisan make:command ShowDatabase
app\Console\Commands\ShowDatabase.php
Add Signature and description in the ShowDatabase.php command.
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class ShowDatabase extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'ShowDatabase';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Show me the Current Database';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$this->info("Current Database Name is:".DB::connection()->getDatabaseName());
}
}
Command Output :
public function handle()
{
$this->info("Current Database Name is:".DB::connection()->getDatabaseName());
}
app\Console\Kernel.php
After adding Signature and description in the ShowDatabase.php command, We need to register our command 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\ShowDatabase::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')->hourly();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
So now if we run the php artisan list command in a terminal, we should see our command signature and description:
Now we are going to run ShowDatabase Command.
php artisan ShowDatabase
While we run our command it will tell which database is connected with our application.