How to Create a Custom Artisan Command in Laravel 8

How to Create a Custom Artisan Command in Laravel 8

Admin
Admin・ 22 September 2021
8 min read ・ 4392 views

Laravel Custom Artisan Command -  Hi coders. ! πŸ‘‹ In this article I will share how to create a custom artisan command in Laravel 8. In this tutorial I will simulate creating a custom artisan command to run the command to add user data to the users table in the database. Custom artisan command that I will make, to replace the flow register user. But first, we better get acquainted with artisans in Laravel.

What's Artisan ?

Artisan is a Command Line Interface or CLI that already included with Laravel. Artisan is in the root of the application as an artisan script and provides a number of commands that can be used to help us when building applications with laravel. To see all available artisan commands, we can use the command;

php artisan
//atau
php artisan list

Each artisan command in laravel also provides a help screen to display or explain the arguments or options of the available artisan commands. To see the help screen, prefix the artisan command name with help:

Example:

php artisan help migrate

Custom Artisan Command

Then, how do we create a custom artisan command? Well, in this article, we will explain a little about the implementation of creating your own artisan command and its implementation.

In addition to using artisan commands provided by Laravel, we can also create our own custom commands. Commands are usually stored in the app/Console/Commands directory; but we are free to choose the location of placement or storage as long as the command can be loaded by composer.

In this tutorial, I'm assuming that we already have a Laravel project ready to use. To create a new artisan command, we can use the make:command artisan command. This command will create a new command class in the app/Console/Commands directory. If the directory does not exist in our laravel project, it will be automatically created the first time we run the artisan make:command command.

Generate new Artisan Command

php artisan make:command AddUser

Okay. Let's create our first custom artisan command. Run the command as above in the terminal to create a custom artisan command with the class name AddUser.

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;
use Hash;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'This artisan command is used to add user data without registering.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $input['name'] = $this->ask('Your name?');
        $input['email'] = $this->ask('Your email?');
        $input['password'] = $this->secret('What is the password?');
        $input['password'] = Hash::make($input['password']);
        User::create($input);
        $this->info('Data added successfully');
    }
}

Then open the app/Console/Commands/AddUser.php file and change the existing code to be as above.

After creating the new artisan command, we need to define values ​​for the signature and description properties. These two properties are used to display commands on the help screen. The signature property also allows us to specify the command input expectations. The handle method will be called when the command is executed. We can put command logic inside this method.

So, from the AddUser.php code as above, when we run the php artisan add:user command it will display a question for name, email password on the terminal screen and will add the data that we input on the terminal screen to the users table in the database.

Let's see the full explanation πŸ‘‡

custom artisan command

Well, the method signature and description will be displayed on the terminal screen as shown above. Please try running the php artisan command or php artisan list, then look for the custom artisan command that was created in the AddUser.php file.

display description of artisan command

Or use the command php artisan help add:user to display the specific details of the command.

Run Custom Artisan Command

run custom artisan command

To run our custom artisan command in laravel, we only need to run the php artisan add:user command, then several questions will appear such as name, email and password, then the data that has been inputted will be added to the users table in the database and display the message " Data added successfully".

How to add confirmation ?

If you need to add confirmation (yes or no) when executing the artisan command, we can use the confirm method. By default, this method will return false, but if the user inputs y or yes as a response, this method will return true.

if ($this->confirm('Do you wish to continue?')) {
    //
}

We can specify that confirm will return true by default by passing true as the second argument to the confirm method like the example below.

if ($this->confirm('Do you wish to continue?', true)) {
    //
}

Displaying Table with Artisan Command

php artisan make:command Users

The second example, we want to display the data in the users table using the custom artisan command that we have created. To make it, we create another custom artisan command using the command as above.

use App\Models\User;

Then open the Users.php file located in the app/Console/Commands directory. add trait use App\Models\User; like the example above.

protected $signature = 'users';

Next, in the method signature we just make it simple with users.

public function handle()
{
    $this->table(
        ['Name', 'Email'],
        User::all(['name', 'email'])->toArray()
    );
}

Now, for the handle method, use the code as above to display the data from the users table in the form of an array.

run custom artisan command laravel 8

Okay, now we try to run the artisan command that has been made to display data from the users table using the php artisan users command. Then the output displayed after running the command will be like the image above.

Run Artisan Command in Tinker

We can also run artisan commands via tinker in laravel. Tinker allows us to interact with all of our Laravel applications using the command line, including eloquent models, jobs, events and others. To use tinker, we can use the php artisan tinker command.

php artisan vendor:publish --provider="Laravel\Tinker\TinkerServiceProvider"

Before we can use the artisan command in tinker, we need to publish the tinker configuration file using the command as above.

'commands' => [
    App\Console\Commands\AddUser::class,
    App\Console\Commands\Users::class,
],

Then open the file in config/tinker.php and list the custom artisan command class that we have created in the array like the example above.

run laravel artisan command in tinker

OK, now we can run the laravel artisan command on tinker by using the initial php artisan tinker command and followed by the artisan command that has been created like the example image above.

That's a tutorial article on creating custom artisan commands in Laravel 8. We've learn how to create a simple custom artisan command in laravel, from creating an artisan command to add data to the users table, displaying data from the users table using the artisan command, and at the end of the article we also learned how to run artisan. commands in tinker laravel 8.

For a complete explanation of artisan in Laravel, you can learn on the Laravel official website or by clicking the link below. Hopefully this article can be useful and see you in the next article.πŸ‘‹

 

Full Documentation: Laravel Artisan Command

Tinggalkan Komentar
Loading Comments