X
    Categories: Learn Laravel Tutorials, Tips And Guides

Create Custom Artisan Commands with Laravel

Artisan is a command line utility that comes with Laravel, one of the most popular PHP frameworks.This utility is extensively used for setting up migrations, routes listings, queueing, class creations, and other related tasks.

For a complete list of tasks that Artisan could help with, run the following command inside the Laravel project directory:

public_html $>  php artisan
Laravel Framework version 5.3.19
...
...

Make is an important command in Artisan, used for creating custom Artisan commands.

make
 make:auth        	Scaffold basic login and registration views and routes
 make:command     	Create a new Artisan command

If you have a task which often pops up during your projects, create an Artisan command, add the code into the class, and fire away from the CLI. Optionally, add the Artisan command as a cron job.

Lining up the Ducks in a Row

Let’s say you have a hypothetical service based app with a table named transactions. This table stores all the transactions of the app.

Every week, this script checks whether there are any unpaid bills for transactions in the last 30 days. If any such transactions are discovered, the system sends the user an email.

I will first create the boilerplate class using Artisan commands:

public_htm $> php artisan make:command NotifyLateUsers --command=notify_unpaid_users
Console command created successfully.

Next, register the class in app/Console/Kernel.php. In this case, It would look like the following:

protected $commands = [
   	//
   	Commands\NotifyLateUsers::class
	];

The actual class is stored in app/Console/Commands/NotifyLateUsers.php. Here’s a quick overview of the class:

protected $signature = 'notify_unpaid_users';

This is the actual command that will be executed from the command line for invoking the script.

protected $description = 'Command description';

The description which will show up with the command when  php artisan  is called.

public function __construct()

The constructor to the command that is used for any initial setup.

public function handle()

This function contains the main body of our command.

At this point, run php artisan:

public_htm $> php artisan
Laravel Framework version 5.3.19
…
Available commands:
...
 notify_unpaid_users  Command description
…

From here on, it’s just simple coding. I will first retrieve all records of users who have unpaid transactions. Then I will check if the due date has passed for that transaction. If it has, I will roll out an email. Here’s the code:

function mail_utf8($to,
  	    	            $message,
  	    	            $from_user = 'Billing',
  	                   $from_email = 'support@yourxyzcompanyname.com',
  	    	            $subject = 'Reminder to pay your dues.')
	{
  		$from_user = "=?UTF-8?B?".base64_encode($from_user)."?=";
  		$subject = "=?UTF-8?B?".base64_encode($subject)."?=";

  		$headers = "From: $from_user <$from_email>\r\n".
                        "MIME-Version: 1.0" . "\r\n" .
             	     "Content-type: text/html; charset=UTF-8" . "\r\n";

 	       return mail($to, $subject, $message, $headers);
	}

	public function handle()
	{
   		$this->info("Getting DB records of offending users...");
   		$transactions = DB::connection('mysql')->select('select * from transactions where status = "not_paid"');

   		foreach ($transactions as $t) {
   			$t_date = DateTime::createFromFormat('Y-m-d H:i:s', $t->date_generated);

   			# Add 30 days to transaction date to get due date.
   			$due_date = $t_date;
   			$due_date->add(new DateInterval('P30D'));
   			$current_date = DateTime::createFromFormat('Y-m-d H:i:s', date('Y-m-d H:i:s'));

   			$t1 = $t_date->format('d/m/Y'); // for example    
   			$d = $due_date->format('d/m/Y'); // for example    
   			$c = $current_date->format('d/m/Y'); // for example    

   			if ($current_date > $due_date){
  				# Sending emails to users   		 
           			$this->info("due_date $d");
  		 		$this->info("current $c");

       			$this->info("Sending email to user: $t->email");
  	 
  	 			$msg = <<<EOT
Hi,
  This is to remind you that we have not received payment for
your transaction dated $t1. The due date was $d, but
payment still has not been received. Please clear your dues as
soon as possible.

Thank You.
EOT;
           			// send email
           			$this->mail_utf8($t->email,$message=$msg);
   			}
   		}    
}

Notice that I added a function called mail_utf8. At the moment, I am sending mail through the PHP mail function. Because of this, the emails will most likely end up in the spam/junk folder. It would have been better to use a mailing service such as Mailgun, Mandrill, SparkPost, etc. Laravel supports some, if not most of the popular mailing services.

Everything else is pretty self explanatory. Here’s a sample run from the CLI:

public_html $> php artisan notify_unpaid_users
Getting DB records of offending users...
due_date 05/12/2016
current 08/12/2016
Sending email to user: <some-email>

And a finally, let’s check the inbox…

Conclusion

In this concise article, I introduced Artisan and then elaborated how you could use this excellent command line tool for setting up frameworks and classes. If you would like to contribute to the discussion or would like to know more about Artisan, please leave a comment below.

Fahad Saleh: Fahad Saleh is a DevOps Engineer at Cloudways