Laravel Custom Artisan Commands: 3 Simple Steps

This article is all about, how you can create your own custom artisan commands in Laravel. This is very easy step to step guide, from which you can achieve creating custom artisan commands.

Step to Create Laravel Custom Artisan Commands

Step 1:

To create a new command, you may use the make:command Artisan command. This command will create a new command class in the app/Console/Commands directory. Don’t worry if this directory does not exist in your application – it will be created the first time you run the make:command Artisan command:

php artisan make:command SendEmails

Step 2:

After generating your command, you should define appropriate values for the signature and description properties of the class. You can specify the input requirements for your command by using the signature property. You may place your command logic in this handle method.

Let’s take a look at an example command.

<?php
 
namespace App\Console\Commands;
 
use App\Models\User;
use App\Support\DripEmailer;
use Illuminate\Console\Command;
 
class SendEmails extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mail:send {user}';
 
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send a marketing email to a user';
 
    /**
     * Execute the console command.
     */
    public function handle(DripEmailer $drip): void
    {
        $drip->send(User::find($this->argument('user')));
    }
}

Step 3:

Now it’s time to check your command in terminal.

php artisan mail:send 1

The above command will find the user having id 1 and triggers a marketing email to that particular user.

Now, we learn to create our laravel custom artisan command.

Leave a Reply

Your email address will not be published. Required fields are marked *