Create a Laravel Custom Artisan Command

You can create your artisan command in Laravel and run it anytime from the terminal. In this topic, we will see how you can create a Laravel custom Command and run it from the command line. You can use the Laravel "create command" to create your new command and use it as an artisan command.

Watch YouTube Video

Create a Laravel project

Let us create a project in Laravel 10. Make sure you have Composer and PHP installed in your system. I have given the project name lara_command.


composer create-project --prefer-dist laravel/laravel lara_command

You will see a folder named "lara_command" created under the folder from where you run the above command.

MySQL Database setup and Migration

Update the .env file for the database details. In this case, we are using a MySQL database named 'lara_command', so we updated the file as below:


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=lara_command
DB_USERNAME=root
DB_PASSWORD=

We will create a new table named "trainings", so we need to create a Laravel migration for the new table. This table will store the details of all the courses. Go to your project folder and run the below command from the VS code terminal to create the model, controller and migration.


php artisan make:model Training -mc

The bove command will create the model, controller and migration file. I am using VS code and three files are marked below:

laravel create command example

Migration for the custom table

Let us update the Laravel migration file for the table 'trainings'.


<?php
  public function up(): void
    {
        Schema::create('trainings', function (Blueprint $table) {
            $table->id();
            $table->string('course_name');
            $table->text('course_descr')->nullable();
            $table->string('level');
            $table->string('duration');
            $table->timestamps();
        });
      }

Now run the migration to create the default Laravel tables and our custom table using php artisan migrate command. Run the below artisan command from the project root to create the tables.


php artisan migrate

This will create all the default Laravel tables and our custom 'trainings' table. After migration see the structure of the 'trainings' table.

laravel custom artisan command table structure

Let us update the model.

app/Models/Training.php


<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Training extends Model
{
    use HasFactory;

    protected $fillable = ['course_name', 'course_descr', 'level', 'duration', 'created_at', 'updated_at'];
}

Controller

We will create a method createCourse() in TrainingController to insert a row in the 'trainings' table.

We are just creating a simple method to insert a row in the Training model to show how you can call a controller method from the command line.


<?php
 public function createCourse(){
        $data = [
            'course_name'  => 'Java', 
            'course_descr' => 'Core Java Training', 
            'level'        => 'Basic', 
            'duration'     => '3 weeks',
        ];
        Training::create($data);
    }

As this is for testing purposes, we hard-coded the values for the fields. We want to show that the controller method runs successfully from the command line. In the actual controller method, you might have to do some other processing, like, selecting from the multiple tables, doing some transformations, etc, and finally update or insert into a database table.

Create the Laravel Command

Now, we will create a Laravel command. Go to the VS code terminal and run the below command to create a Laravel command from the project root.


php artisan make:command CreateCourseCommand

Command file "CreateCourseCommand.php" will be created in app/Console/Commands folder as shown below:

laravel create command

Let us now update this command to call the controller method, created earlier:

app/Console/Commands/CreateCourseCommand.php


<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

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

    /**
     * The console command description.
     *
     * @var  string
     */
    protected $description = 'Command to create a course';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $controller = app()->make('App\Http\Controllers\TrainingController');
        app()->call([$controller,'createCourse']);
    }
}

Our development is done. We have created our Laravel custom artisan command to call the controller creatreCourse() method. If we run this command, it should insert a row in the 'trainings' table. Let us test it now.

Test the application

Before testing, check if any data exists in the 'trainings' table. For our testing, we kept the 'trainings' table empty initially.

From the terminal enter the below command from the project root:


php artisan create:course

It should give a message as "course created". Check the table, a row should be inserted.

laravel custom artisan command

create laravel project cmd

Download Source code from Github.

Post a Comment

Save my Name and Email id for future comments