Create Custom Artisan Command in Laravel

Chandresh
CS Code
Published in
2 min readJun 14, 2020

Artisan is a frequently used command-line interface that comes with Laravel which provides a set of commands that are helpful while building your application.

Let’s say you want a command to automatically email getting started guide link to users 1 day after registration.

If you would like to watch me doing this then here is the tutorial.

Let’s Start!

Create a new command using command:

php artisan make:command SendDocLinkToUsers

Open app/Console/Commands/SendDocLinkToUsers.

Set name and signature of your command and write a small description about your command.

Inside handle function you can write your logic. It should look something like this:

Create Email Notification that we want to send to users.

php artisan make:notification SendDocLinkNotification

Make changes in app/Notifications/SendDocLinkNotification file as per your liking.

public function toMail($notifiable)
{
return (new MailMessage)
->line('Thanks for registering. Below is the link to our get started guide.')
->action('View Get Started Guide', url('/getting_started_guide_url'))
->line('Feel free to reply to this email if you need any help in getting started.');
}

Try running the command

php artisan users:send_doc_link

Now to run it auto automatically everyday, all you need to do is set the command in Laravel scheduler. You can do this in app/Console/Kernel.php

protected function schedule(Schedule $schedule)
{
$schedule->command('users:send_doc_link')->daily()->at('08:00');
}

Or You can even use crontab to run the command everyday.

*Note: For running Laravel scheduler you will have to set the command in either crontab or supervisor to run every minute.

You can learn more about Laravel scheduler here.

You can find the entire code here

That’s it!

Hope you find it useful.

Originally published at https://dev.to on June 14, 2020.

--

--