Making a custom Artisan Command in Laravel 5.4

There are several default artisan commands that come with laravel, the common ones are php artisan serve,php artisan migrate, php artisan make:migration and the likes of them.

Introduction

The more an application grows the more important it becomes to automate certain tasks. If you are a junior developer or an intern that doesn’t have access to a server to run some certain commands like running a migration, you’ll have to buzz the devops engineer to help you run a migration (after your code has been reviewed and merged to the live branch tho ). Automating these tasks will go a long way to help you and the devops engineer. With that being said we’ll go over making a custom laravel artisan command to add data to the DB(Database) in the following steps.

Steps:

Step 1: Install Laravel.
 Step 2: Run php artisan make:command userData.
 Step 3: Create signature and description for your command in app/Console/Command.
 Step 4: Add your command logic in the handle() function.

Step 1

I’ll assume you have Laravel installed.

Step 2

Open your terminal in your “project directory” and run the following command
 php artisan make:command userData.

This command creates a file in the app/Console/Commands directory called userData.php which looks like:

<?php 
namespace App\Console\Commands;
use Illuminate\Console\Command;
class userData extends Command {
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'command:name';
    /**  
* 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()
{
//
}
}

Step 3

Now let’s create the actual command, we’ll set $signature to add:user_id and $description = Add user data to database.

If you run php artisan list in your terminal you will find out that our command does not exist yet, that's because it has not been registered. To register the command we'll navigate to app/Console and open up the Kernel.php file, we will then add this line of code Commands\userData::classto the $commands array defination. It should look like this:

<?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\userData::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 Closure based commands for the application.
*
* @return void
*/
protected function commands()
{
require base_path('routes/console.php');
}
}

So now if we run php artisan list we should see our command signature and description:

Step 4

Now to give our php artisan add:user_data command life, I will assume you have a users database with columns name, email, password. If you don't, run php artisan migrate and you'll be fine. Next thing is to convert our csv file to an array and add it to the database like:

<?php 
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\User;
class userData extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
      protected $signature = 'add:user_data';    
/**
* The console command description.
*
* @var string
*/

protected $description = 'Add user data to database';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle(){
$file = public_path('user_data.csv');
$delimiter = ',';
if(!file_exists($file) || !is_readable($file))
return false;

$header = null;
$data = array();
         if (($handle = fopen($file,'r')) !== false){
while (($row = fgetcsv($handle, 1000, $delimiter)) !==false){
if (!$header)
$header = $row;
else $data[] = array_combine($header, $row);
}
fclose($handle);
}
      $meta_descArr = $data; 
for ($i = 0; $i < count($meta_descArr); $i ++){
User::firstOrCreate($meta_descArr[$i]);
}
echo "Users data added"."\n";
}
}

Now for the moment we have been waiting for, run php aritsan add:user_data.

If you got this response Users data added. Can i get an Air five!!?.

Conclusion

In less than 20 minutes we have learned how to create a custom artisan command in laravel 5.4, here’s a link to the source code. This is just one of the many cool things you can do with your custom artisan commands. You could create commands that accept inputs. This would be very helpful if you want to woo that pretty devops engineer that you have to bug every time you want to run artisan commands on the server. You could make a chatbot that gets input from here and send it directly to your email, you reply and she sees the reply on the terminal. Hmm… I guess that is a topic for another day. Like a wise man once said We are gods, Think it, and it shall come alive.


Originally published at dev.to.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.