Want to build your own application using commands? Artisan is a widely used command-line interface that comes with Laravel, which provides you the power to build your own applications with ease.
We can use the ‘make:command’ artisan command to develop a new artisan command. This command will create a new command class in the app/Console/Commands catalog.
When we run the Artisan ‘make:command’ command for the first time, it will be created for us immediately if the directory doesn’t already exist in our Laravel project.
Laravel, one of the most well-known PHP frameworks, comes with the command-line tool Artisan. Setting up migrations, route listings, queueing, creating classes, and other related operations considerably use this application.
But before creating Custom Artisan Commands, let’s first understand what Artisan and Laravel is.
What is Artisan & Laravel?
Firstly, Artisan and Laravel are two different things – Artisan is a Command-line interface (CLI) & Laravel is a PHP framework.
Let’s first understand Artisan. Artisan helps you build your application using commands. Artisan Command-line interface (CLI) uses Laravel as a framework.
For example, Artisan allows you to construct new migrations, models, and controllers. It may also run unit tests, serve your application locally, and push it to production.
Awesome things you can do with Artisan:
- Create new Laravel applications
- Generate migrations, models, and other code
- Seed your database with dummy data
- Run unit tests
- Serve your application locally
- Deploy your application to production
Secondly, Laravel is a one-source PHP web framework created by Taylor Otwell that provides several features that make your job easier to develop web applications. Laravel is well-known for its clean syntax, robust features, and enormous community. It is an excellent alternative for both beginner and expert developers.
Some of the features are:
- A Model-View-Controller (MVC) architecture
- A powerful routing system
- A robust database abstraction layer
- A comprehensive testing suite
- A large community of developers
Which version of Laravel is best for you?
The optimal selection of Laravel depends on individual needs and requirements. Laravel undergoes continuous updates, incorporating new features and enhancements. Therefore, choosing a version that aligns with the specific feature set required is crucial.
Here is a technical comparison of the most recent versions of Laravel:
Laravel 9:
- Release Date: February 8, 2022
- Notable features: Enhanced support for PHP 8, anonymous stub migrations, and a new query builder interface
- Currently undergoing active development, thus may contain certain bugs or issues
Laravel 8:
- Release Date: September 8, 2020
- Notable features: Support for PHP 8, Blade components, and a new filesystem abstraction layer
- Stable release with reduced likelihood of bugs or issues
Laravel 7:
- Release Date: March 2, 2020
- Notable features: Support for PHP 7.4, Laravel Spark, and a new queue system
- Stable release with reduced likelihood of bugs or issues
For individuals new to Laravel, it is recommended to begin with Larvel 8. This version offers a stable release with numerous features, which is an excellent starting point for learning Laravel.
If access to the latest features is required, an upgrade to Laravel 9 can be considered. However, it is important to note that Laravel 9 is currently in active development, which may entail the presence of certain bugs or issues.
When selecting a version of Laravel, the following factors should be taken into account:
- Needs: Consider the specific features required in a web framework.
- Experience level: Determine whether you are new to Laravel or possess experience with other frameworks.
- Team requirements: Evaluate the needs of team members.
- Release stability: Assess whether the release is stable or still in development.
Considering these factors, the appropriate version of Laravel can be chosen to suit individual requirements.
Setting up New Custom Artisan Command
To create a custom Artisan command in Laravel, we have used Nestify’s demo as an example. All you need to do is follow the steps below if you have an account on Nestify or with any other host provider:
Note: For e.g., we are taking the name of DemoNestify.
- Open a command prompt and browse to the root directory of your Laravel project.
- Run the following command.
php artisan make:command DemoNestify
This command will create a new file named DemoNestify.php in the app/Console/Commands directory of your Laravel project.
- Open the generated ‘app/Console/Commands/DemoNestify’ file, and you will see a class name ‘DemoNestify.’ This class extends the Illuminate\Console\Command base class and represents your custom Artisan command.
- Customize the command with a name, description, and signature for display and invocation.
Once you bring about the customization mentioned above, it should look something like this:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class DemoNestify extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = ‘demonestify:create-employee-account’;
/**
* The console command description.
*
* @var string
*/
protected $description = ‘Create an employee account’;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// Logic to create employee account goes here
}
}
Now, let’s proceed to update the Laravel command we created earlier in Nestify’s demo account. We will now use the `$user` variable to create an admin and the `$description` variable to create a user account with an admin role. We must also update the `role` field in the `users` table.
After making these updates, if you run `php artisan` in Laravel, you will encounter an unexpected error stating that the command does not exist. This is majorly because the command is not registered and recognized by the terminal. To register the command, we need to update the `Kernel.php` file inside the `app/Console` directory.
Open the `Kernel.php` file and add the following line within the `protected $commands` array:
protected $commands = [
Commands\DemoNestify::class,
];
Once you have updated the command in `Kernel.php,` you can use the newly created command. You can also verify its registration by running the `php artisan list` command, which will display a list of available commands.
Database Migration
The command we created still needs to implement Logic. To proceed further, let’s create migration tables using the following command:
php artisan make:migration create_users_table
After running this command, check your migration folder, and you will find a newly created migration table file. You can customize the migration by adding or modifying table columns within the migration file’s `up()` and `down()` functions.
protected $fillable = [
‘name’, ’email’, ‘password,’ ‘role’
];
Specifying the fillable fields allows these attributes to be mass assignable when creating new model instances.
Next, within your command class’s `handle()` method, you can implement the Logic to create the user account according to your requirements.
Here’s an example code snippet:
public function handle()
{
$newUser = [
‘name’ => ‘AYX’,
’email’ => ‘[email protected]’,
‘password’ => bcrypt(‘secret’),
‘role’ => ‘Manager’
];
//Logic to create a user account with the $newUser data
}
Customize the values in the `$newUser` array to match your desired user account details. This code snippet demonstrates an example of creating a new user with the name ‘AYX’, email ‘[email protected]’, password ‘secret’, and role ‘Manager’.
Add the necessary Logic inside the `handle()` method to create the user account and perform any additional operations as required.
Conclusion
Using Laravel’s proprietary Artisan command, you may expand the functionality of your apps and automate repetitive activities. Thanks to the step-by-step instructions offered in this post, you can and know how to construct your own custom commands in Laravel.
Utilize Artisan’s capacity to expedite your development process by creating commands that cater to the unique demands of your apps. Have fun coding!
(FAQs) on custom Artisan command
Is it possible to pass arguments to a custom Artisan command?
Absolutely! You have the ability to pass arguments to your custom Artisan command by specifying them in the signature property of your command class. For instance, if you wish to pass a name argument to your command, you can define the signature as custom:command {name}. Inside the handle method, you can access the value of the argument using the $this->argument(‘name’) method.
How can I provide options to my custom command?
To include options in your custom command, you can define them in the signature property of your command class using the – option syntax. Suppose you want to add a – force option to your command. In such a case, you can define the signature as custom:command {name} –force. Inside the handle method, you can access the value of the option using the $this->option(‘force’) method.
Can I automate the execution of my custom Artisan command?
Absolutely! Laravel offers an incredible task-scheduling feature that permits you to automate the execution of your custom Artisan commands at specific intervals. By implementing the schedule method in the App\Console\Kernel class, you can schedule your command to run naturally. For detailed information on scheduling commands in Laravel, please refer to the Laravel documentation.
Can I make my custom command interactive and prompt the user for input?
Certainly! Laravel provides an ask method that facilitates interaction with the user and allows you to obtain input within your custom Artisan command.
You can utilize this method to prompt the user for input and incorporate the input within your command’s logic. For instance, you can use $this->ask(‘What is your name?’) to prompt the user to enter their name.
Is it possible to create multiple custom Artisan commands in a single file?
While it is technically feasible to define multiple custom Artisan commands within a single file, it is generally advisable to create separate files for each command. This approach helps maintain code organization and readability. Ideally, each command should have its own dedicated file within the app/Console/Commands directory.