This tutorial is out of date and no longer maintained.
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.
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.
- 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.
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:
- 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:
<?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()
{
//
}
}
Now proceed to create the actual command by editing the file we just created:
<?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.
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.
<?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:
- 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!
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:
- 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:
...
class Product extends Model
{
protected $table = "products";
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'description', 'quantity'
];
}
And:
<?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()
{
...
}
}
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
- php artisan migrate
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.
<?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
- 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.
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.
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!