How to Create a custom artisan command in Laravel 9 Framework using an example ?

Laravel

Artisan is the name of the command-line interface included with Laravel. It provides a number of helpful commands that can assist you while you build your application. Artisan can also be used to execute your own custom commands. 

Here at Fixwebnode, We shall look into how to create a custom artisan command in Laravel 9 Framework.

 

How to Create an Artisan command in Laravel 9 ?

To create a custom artisan command in Laravel 9, we must first create a new command class.

We can do this by running the make:command Artisan command. This command will generate a new command class in the app/Console/Commands directory.

For example, if we want to create a command called "HelloWorld", we can run the following command:

$ php artisan make:command HelloWorld

This will create a new file called HelloWorld.php in the app/Console/Commands directory. 

Open this file and add the following code:

namespace App\Console\Commands; 
use Illuminate\Console\Command; 
class HelloWorld extends Command 
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'hello:world'; 
    /**
     * 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()
    {
        $this->info('Hello World!'); 
    }
}

This command will simply print "Hello World!" to the console when it is executed.

 

How to test the created Artisan command ?

To test our command, we can run the following command in the terminal:

$ php artisan hello:world

This will execute our command and print "Hello World!" to the console.

 

We can also test our command in a web browser.

To do this, we need to create a route that will execute the command when it is accessed. 

We can do this by adding the following route to the routes/web.php file:

Route::get('/hello-world', function () {
    Artisan::call('hello:world'); 
});

Now, if we visit the /hello-world route in a web browser, our command will be executed.

 

[Need help in fixing Laravel issues ? We can help you. ]

 


Conclusion

Your Cart