Hi all,
I’m quite new to Laravel and so far I really like it, especially the artisan
commands. Has anyone created a custom artisan
command? If so can you please share the steps that I would have to take in order to do so?
Thanks!
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!
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
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:
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:The output that you would get should look something like this:
Output:
This would create a file called
HelloWorld.php
in theapp/Console/Commands
directory.The content of the file should be similar to this one here:
Once you have your command generated, you need to update the
name
and thedescription
properties for the newHelloWorld
class. To keep things as simple as possible I would just usehello
as the name andPrints Hello World
as the description.Now you should be able to see your new command in the Artisan list:
Output:
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 yourhandle
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 returnHello World!
as the output, so the piece of code that needs to go there is: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
When I type ls, I can see my files, but when I type php artisan… I got the message: Could not open input file: artisan
I’m in /srv/users/myappname/apps/myappname/public
all the files from my laravel project are in public folder.
Thanks for guidance as I’m not a developper.
When I type: php artisan make:command HelloWorld in the console, I get this error message: Could not open input file: artisan