DEV Community

Nkere-Awaji Inwan
Nkere-Awaji Inwan

Posted on

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()
    {
        //
    }
}
Enter fullscreen mode Exit fullscreen mode

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');
    }
}
Enter fullscreen mode Exit fullscreen mode

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";
    }
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (4)

Collapse
 
azazqadir profile image
Muhammad Azaz Qadir

I love artisan commands. You can use PHP artisan create table command to quickly create table for database. Artisan commands has made coding for laravel developers easy.

Collapse
 
florianmuellerch profile image
florianmuellerCH

Here we are in 2020 and your gif in 2017 was already practicing social distancing. Clearly you knew what would come.

Nice post btw! Helped me a lot to get into creating commands :)

Collapse
 
backendcoding profile image
backendcoding

I have been trying to find this out. Maybe you can help me. I was wanting to know do you have to remake these commands for different projects or new projects that you make?

Collapse
 
enkaypeter profile image
Nkere-Awaji Inwan

Yeah you have to. If you check the list of artisan commands using php artisan list, the custom command you make for project A won't be visible in project B.In other words, The commands are project specific