Key Takeaways:
- PHP Artisan is a command-line tool that simplifies common Laravel development tasks, from generating code to managing migrations.
- Custom Artisan commands can be created to automate repetitive project-specific tasks, improving developer efficiency.
- Artisan offers a range of built-in commands for actions like running a development server, managing caches, and interacting with the queue system.
Ever wanted to make repetitive tasks in your Laravel app automatic?
Well, PHP Artisan, a handy command-line tool that comes with Laravel, can help you do just that. It allows you to automate tasks, manage resources, and interact with the Laravel framework seamlessly.
To create a new Artisan command, use the make:command command. This will create a new command class in the app/Console/Commands directory. It’s used for setting up migrations, route listings, queueing, class creation, and other tasks.
From the basics of Artisan Commands to creating and running your own custom commands, this article covers everything you need to know about PHP Artisan in Laravel 11.
Overview of PHP Artisan
Developers use Laravel Artisan commands to complete important tasks like creating migrations and publishing package assets.
There are built-in Laravel commands and the option to create custom commands. Laravel Artisan has many pre-made commands available.
To view a list of these commands, type php artisan list in your terminal. This will provide you with a list of all the available Laravel Artisan commands.

These commands help developers work more efficiently, thereby saving them precious time. Using these Laravel Artisan commands, you can create auth, controller, model, mail, migration, and many other functions.
Try Custom Commands in Laravel 11 on Cloudways Today!
Create and manage custom commands effortlessly on Cloudways, with unlimited resources and the flexibility of PHP 8.
Basics of Laravel Artisan Commands
Laravel Artisan commands are important for the Laravel framework. They give developers a Command-Line Interface (CLI) to make their work easier and faster.
The Illuminate\Console\Application class is the foundation for Artisan. It extends the Symfony\Component\Console\Application class. This design makes it easy for Symfony developers to use Artisan because it has a familiar environment.
A simple command may appear like this, for instance:
namespace App\Console\Commands;
use Illuminate\Console\Command;
class ExampleCommand extends Command
{
protected $signature = 'example:run {name}';
protected $description = 'Runs an example command';
public function handle()
{
$name = $this->argument('name');
$this->info("Hello, {$name}!");
}
}
Run Laravel with PHP Artisan Server
The Laravel PHP Artisan Serve command makes running applications on the PHP development server easy. As a developer, you can use Laravel Artisan to create and test different application features.
When you run the php artisan serve command, you can quickly start a server at http://localhost:8000. This allows you to test and develop your applications locally. You can also customize the server to use different hosts and ports.
The php artisan serve command works with the Laravel ecosystem. This includes features like database migrations, task scheduling, and queue management.
Create and Run Custom Commands
Laravel’s Artisan provides a list of commands. You can also make your own custom Artisan commands. You can choose where to store them as long as Composer can load them. To create, register, and execute your custom commands, follow these 8 simple steps:
Step 1: Create New Command
Laravel’s Artisan CLI provides a convenient way to generate custom command classes. To create a new command, simply use the make:command Artisan command.
This automatically creates a new command class within the app/Console/Commands directory. If this directory doesn’t exist, it will be generated for you.
Type the following command in the Artisan Console:
php artisan make:command customcommand
The file might look like the following:
namespace App\Console\Commands;
use Illuminate\Console\Command;
class CustomCommand extends Command
{
protected $signature = 'custom:command';
protected $description = 'Description of the custom command';
public function __construct()
{
parent::__construct();
}
public function handle()
{
// Command logic goes here
}
}
Step 2: Define Command
When crafting console commands, you often need to gather information from the user. Laravel handles this through the signature property.
You can use this short syntax to set required and optional arguments and flags. This makes it easy to design how your command works with the user.
protected $signature = 'user:update {id} {--name=} {--email=}';
The command expects an ID argument and optional name and email options in this example.
Step 3: Command I/O
When you run a command, Laravel gives you easy ways to get the values of arguments and options. In your command’s handle method, use the $this->argument() and $this->option() methods.
If the argument or option you’re looking for doesn’t exist, these methods will return null.
To Prompt for Input
You can get user input while your command is running, in addition to displaying output. The ask method will show the user a question, collect their response, and then send it back to your command.
$name = $this->ask('What is your name?', 'Taylor');
To Ask for Confirmation
if ($this->confirm('Do you wish to continue?')) {
// Continue
}
You can make the confirmation prompt always return true. To do this, pass true as the second argument to the confirm method.
Step 4: Register Commands
Laravel, by default, registers all commands located in the app/Console/Commands directory. You can set up Laravel to look in more directories for PHP Artisan commands. To do this, use the withCommands method in your app’s bootstrap/app.php file.
->withCommands([ __DIR__.'/../app/Domain/Orders/Commands', ])
When you use Artisan, the service container will find and register all the commands in your application with Artisan.
Step 5: Execute Demands
Sometimes, you might want to run an Artisan command outside the CLI, such as from a route or controller. You can achieve this using the call method on the Artisan Facade.
This method has two arguments. The first argument is the command’s name or class. The second argument is a list of command parameters. The method returns the exit code.
You can also pass the entire Artisan command to the call method as a string:
Artisan::call('mail:send 1 --queue=default');
To Queue Artisan Commands
You can use the queue method on the Artisan facade to send Artisan commands to your queue workers. These commands will then be processed in the background. Before using this method, make sure that your queue is configured and a queue listener is running.
use Illuminate\Support\Facades\Artisan;
Route::post('/user/{user}/mail', function (string $user) {
Artisan::queue('mail:send', [
'user' => $user, '--queue' => 'default'
]);
// ...
});
Step 6: Signal Handling
Laravel Artisan commands can handle system signals like SIGINT. You can incorporate signal handling into your command using the trap method.
$this->trap(SIGINT, function () {
$this->info('Command interrupted');
});
Step 7: Stub Customization
You can customize the template files used by the make:command Artisan command to make it easier to create commands with consistent structures.
To do this, you need to publish the stub files to your project.
php artisan stub:publish
Step 8: Events
There are three events that Artisan dispatches when running commands:
- Illuminate\Console\Events\ArtisanStarting
- Illuminate\Console\Events\CommandStarting
- Illuminate\Console\Events\CommandFinished
Use the event method to fire an event:
event(new CustomCommandExecuted($this));
Create Migrations with make:migration
php artisan make:migration is a Laravel Artisan command used to create a new migration file. Migrations are essentially blueprints for your database schema. They define the structure of your tables, columns, indexes, and relationships.
Here is what the process looks like:
- Create a Migration: When you run the make:migration command, it creates a new PHP file in the database/migrations folder.
- Define Changes: The migration file contains up and down methods. The up method defines changes to the database, like creating tables or adding columns. The down method undoes those changes.
- Run the Migration: To apply the changes to your database, use the php artisan migrate command.
Example
Bash php artisan make:migration create_users_table
This command will make a new file called create_users_table in the database/migrations folder. You can then define the users table structure within the migration file.
Benefits of make:migration
- Version control: Track database changes over time.
- Collaboration: Easily share database structure with team members.
- Database seeding: Populate your database with test data using seeders.
- Database rollbacks: Easily revert database changes if needed.
Migrations help you keep your database schema clear and organized. This makes it easier to manage and update your application.
List of Laravel Artisan Commands
Laravel’s Artisan CLI is a useful tool for working with your app. It has different commands for different tasks, like making code and managing the app’s environment.
A complete Laravel PHP Artisan commands list would be extensive. You can use the PHP Artisan list command to fetch it, but here’s a breakdown of the primary command categories in Laravel 11:
Core Commands
- cache: Manage the application cache (clear, forget, etc.)
- config: Cache, clear, or publish configuration files
- down: Temporarily disable the application
- env: Manage environment variables
- key: Generate a new application key
- migrate: Run database migrations
- optimize: Optimize the application for production
- queue: Manage the queue system
- route: List or clear routes
- storage: Manage the storage directory
- vendor: Manage Composer dependencies
Code Generation Commands
- make: Generates various code structures (controller, model, migration, etc.)
- model: Creates Eloquent models
- migration: Creates migration files
- seed: Seeds the database with dummy data
Testing Commands
- test: Runs application tests
- dusk: Runs browser tests with Dusk
Other Commands
- auth: Manages authentication-related operations
- breeze: Installs Breeze authentication system
- config: Manages configuration files
- horizon: Manages the Laravel Horizon queue system
- passport: Manages OAuth2 server
- sanctum: Manages API token authentication
- telescope: Manages the Telescope debugging tool
You can also schedule recurring tasks or automate repetitive commands using Laravel cron job.
Summary
In this article, we have shown how to create custom commands using the Artisan command. Artisan is a PHP tool that allows you to develop different commands based on your project’s needs.
If you have any questions about this article or the Artisan command, please feel free to leave a comment below. We are happy to help.
Frequently Asked Questions
Q. What is the purpose of Laravel PHP Artisan commands?
A. Artisan commands are a command-line tool in Laravel. They help you automate tasks, manage migrations, and generate code scaffolding. You can also use them to run tests and do other development and management tasks in your Laravel applications.
Q. Why use PHP Artisan Serve?
A. The PHP Artisan serve command quickly launches a local development server for your Laravel application. It’s ideal for rapid prototyping and testing during development.
Q. How to run PHP Artisan commands in cpanel?
- Open the Terminal from cPanel.
- Navigate to your Laravel project directory using cd /path/to/your/project.
- Run the command with PHP: /usr/local/bin/php artisan {command}.
Make sure to replace /usr/local/bin/php with the correct PHP path for your server, which you can find in the MultiPHP Manager in cPanel.
Q. Can I override or extend existing Artisan commands in Laravel?
A. Certainly! In Laravel, you have the ability to modify or extend existing Artisan commands. To do this, create a custom command that inherits from the base command class. Within this custom command, you can then implement the specific logic or functionality that you desire.
Q. Can I use custom Artisan commands to automate common tasks in my Laravel project?
A. Of course, you can use custom Artisan commands in Laravel to automate common tasks. These tasks may include running migrations, seeding the database, generating code, performing scheduled tasks, and executing any custom logic. Custom Artisan commands provide a convenient and efficient way to automate repetitive actions in your Laravel project.
Hafsa Tahir
Hafsa is a content marketer who has been in the organic growth space for the past three years. With her background in Psychology and UX, she enjoys reading users' minds and is keen to try the most creative product marketing angles. Her copies scream: "you're not just a paycheck to us". Loves to crack unfunny jokes, pay gym fee and not go, and write psychologically disturbing short stories for some reason.