Hello,
Yes, artisan is great, you could use it to automate a lot of tasks.
I’ll try to walk you through the process of creating a simple “Hello World!” artisan command.
Prerequisites:
- You need to have Laravel installed. You can follow the steps on how to do that here if you don’t have it installed yet:
https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-laravel-with-lemp-on-ubuntu-18-04
First, we will build the command. To create a new Artisan command you can use the make:command
artisan command:
php artisan make:command HelloWorld
The output that you would get should look something like this:
Output:
- Console command created successfully.
This would create a file called HelloWorld.php
in the app/Console/Commands
directory.
The content of the file should be similar to this one here:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class HelloWorld 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()
{
//
}
}
Once you have your command generated, you need to update the name
and the description
properties for the new HelloWorld
class. To keep things as simple as possible I would just use hello
as the name and Prints Hello World
as the description.
...
protected $signature = 'hello:world';
...
protected $description = 'Prints Hello World';
...
Now you should be able to see your new command in the Artisan list:
php artisan list | grep -i hello
Output:
- hello:world Prints Hello World
Now if you run your command: php artisan hello:world
you would not get any output. This is because you do not yet have any content in your handle
method. That is where you need to put the logic for your command and the things that you would like it to do. In our case we want to just return Hello World!
as the output, so the piece of code that needs to go there is:
...
public function handle()
{
$greeting = "Hello World!";
print "$greeting \n";
}
...
That is pretty much it, now if you run your command you should see the following output:
Output:
This is pretty much it, of course, this is a really basic example, you could add a lot of logic and arguments depending on what you would like your command to do, but this should be enough to get you started!
Also, I would recommend checking the official documentation here:
https://laravel.com/docs/5.0/commands
Hope that this helps!
Regards,
Bobby