Post

Automate Tasks by Creating Custom Artisan command in Laravel

Draft updated on Invalid Date
author

Olususi Kayode Oluyemi

Automate Tasks by Creating Custom Artisan command in Laravel

This tutorial is out of date and no longer maintained.

Introduction

Out of the box, Laravel comes installed with a lot of helpful commands available to use in an application. But as your application grows, you might find it time-wasting, performing some tasks like populating databases with user data or products.

At this point, automating those tasks will go a long way to help you get data into your database seamlessly and facilitate the rapid completion of your web application.

Some of the default Artisan commands for Laravel include php artisan serve, php artisan make:controller, php artisan make:model, and so on.

In this article, we will be creating an artisan command to populate the database with product data. This tutorial will not only show you how to create a custom artisan command but more so to read data from a CSV file, parse and store it in our database using the command we are going to create.

Install Laravel

To get started with the custom artisan command, I want to assume that you already have Laravel installed, if not quickly do that with the following commands. As of the time of writing this tutorial, Laravel 5.5 is being used.

  1. composer create-project --prefer-dist laravel/laravel command

The command will create a Laravel project called command in your local directory. Feel free to change as preferred.

Generating Commands

Now that you have installed Laravel, let’s proceed to build our own custom commands as stated earlier. To create a custom command, use the command:

  1. php artisan make:command productData

The intention is to create a custom command to populate the products table, hence the reason for the name productData. After successfully running this command, a new class will be created in the app/Console/Commands directory within your project.

Open app/Console/Commands/productData, you should have content similar to:

app/Console/Commands/productData.php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class productData 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()
    {
        //
    }
}

Command Structure

Now proceed to create the actual command by editing the file we just created:

app/Console/Commands/productData.php
<?php

namespace App\Console\Commands;

use App\Product;
use Illuminate\Console\Command;

class productData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'add:product';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Add products data to the database';

    public function __construct()
    {
        ...
    }

    public function handle()
    {
        //
    }
}

Here, we have changed the name and signature of the command and also added the command description. This will be used when displaying the command on the list screen.

Register Command

We are close, but unfortunately, our newly created command will have no effect yet; as it does not exist, as far as Laravel is concerned. To change this, we will need to register the command by navigating to app/Console/kernel.php file and place the Command class we just created in the protected $commands array.

app/Console/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\productData::class,
    ];

    protected function schedule(Schedule $schedule)
    {
       ...
    }


    protected function commands()
    {
       ...
    }
}

To check if the command has been registered, run the artisan command:

  1. php artisan list

And that’s it, our command signature and description have been successfully registered as indicated above.

Congratulations! You just created your first custom Artisan command!

Migrating and Creating Table

In order to give our command life, we are going to create a model and migration file for Product, and then complete a function that will execute the console command we created.

Generate a model and migration file with this command:

  1. php artisan make:model Product -m

This will generate two separate files app/Product and database/migrations/create_products_table. Add the contents below respectively:

app/Product.php
...
class Product extends Model
{

    protected $table = "products";
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
      'name', 'description', 'quantity'
    ];
}

And:

database/migrations/create_products_table.php
<?php
...
class CreateProductsTable extends Migration
{

    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('description');
            $table->string('quantity');
            $table->timestamps();
        });
    }


    public function down()
    {
        ...
    }
}

Database Set Up

Open the .env file and add your database details

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your-database-name
DB_USERNAME=your-database-username
DB_PASSWORD=your-database-password

Now run to create tables

  1. php artisan migrate

Execute Command

Once you execute the newly created command, the handle method within productData class will be called. So let’s edit that and place the required command logic in this method.

app/Console/Commands/productData.php
<?php
...
class productData extends Command
{

    protected $signature = 'add:product';

    protected $description = 'Add products data to the database';

    public function __construct()
    {
        ...
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $CSVFile = public_path('products.csv');
        if(!file_exists($CSVFile) || !is_readable($CSVFile))
            return false;

        $header = null;
        $data = array();

        if (($handle = fopen($CSVFile,'r')) !== false){
            while (($row = fgetcsv($handle, 1000, ',')) !==false){
                if (!$header)
                    $header = $row;
                else
                    $data[] = array_combine($header, $row);
            }
            fclose($handle);
        }

        $dataCount = count($data);
        for ($i = 0; $i < $dataCount; $i ++){
            Product::firstOrCreate($data[$i]);
        }
        echo "Products data added successfully"."\n";
    }
}

You can find the sample CSV file used above here.

It’s time to see our custom command at work.

Run

  1. php artisan add:product

You should get a response stating Product data added successfully after running that command.

A quick look at what we now have in the database.

Conclusion

There is a lot more you can effortlessly achieve by creating a custom Artisan command. You can build on this and create more awesome commands to make development very easy for you when using Laravel.

As shown in this tutorial, you can also read data from a CSV file and store it into your database with just a single command line. I hope this tutorial has been very helpful. If you have any questions or thoughts that require clarifications, kindly drop a comment.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Olususi Kayode Oluyemi

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.