DEV Community

Cover image for How to create custom command in Laravel 8
Snehal
Snehal

Posted on • Updated on

How to create custom command in Laravel 8

Laravel provides set of useful commands which is helpful in creating laravel application. We frequently run these command on the command line interface with the help of artisan.

Let say you want to sends motivational quotes daily to all the users through mail. Instead of doing it manually we can create a custom command provided by laravel.

To create a custom command you need to run following command which will create a custom command file.

php artisan make:command SendMotivatonalQuoteCommand
Enter fullscreen mode Exit fullscreen mode

The above command will create a SendMotivatonalQuoteCommand file which contains two protected variable signature and description, and handle method where you can write main logic.

Now open SendMotivatonalQuoteCommand file

  • Set name and signature for your command and provide a short description for what purpose this command is created.

  • Lets write a main logic into handle() method.
    Let's write a logic to select a random motivational quote from array of quotes and select all user. For better understanding refer below code:


<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

use App\Models\User;
use App\Notifications\SendDailyQuotesNotification;
use Illuminate\Support\Facades\Notification;


class SendDailyQuotes extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'quotes:send-daily-quotes';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'This command will send quotes daily to all the users registered
        to this application';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $dailyQuotes = [
            'Theodore Roosevelt' => 'Do what you can, with what you have, where you are.',
            'Oscar Wilde' => 'Be yourself; everyone else is already taken.',
            'William Shakespeare' => 'This above all: to thine own self be true.',
            'Napoleon Hill' => 'If you cannot do great things, do small things in a great way.',
            'Milton Berle' => 'If opportunity doesn’t knock, build a door.'
        ];

        // generate the random key and get its quote in data variable
        $getRandamQuote = array_rand($dailyQuotes);
        $data = $dailyQuotes[$getRandamQuote];


        $users = User::all();       
        $users->each(function ($user) use ($data) {
            Notification::send($user, new SendDailyQuotesNotification($data));
        });

        $this->info('Successfully sent daily quote to everyone.');

    }
}

Enter fullscreen mode Exit fullscreen mode

To send a notification with a quote, we have to create a Notification through the following command.

php artisan make:notification SendDailyQuotesNotification
Enter fullscreen mode Exit fullscreen mode

Open Notification file and add below code

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

use App\Models\User;

class SendDailyQuotesNotification extends Notification
{
    use Queueable;

    public $quote;
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($data)
    {
       $this->quote = $data;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->greeting("Hello {$notifiable->name}, ")
                    ->subject('Daily Quotes')
                    ->line('This daily quotes helps you to stay encouraged')
                    ->line('Quote of the day : ' . $this->quote)
                    ->action('Notification Action', url('/'))
                    ->line('Thank you for using our application!');
    }
}
Enter fullscreen mode Exit fullscreen mode

Now try to run following command

php artisan quotes:send-daily-quotes
Enter fullscreen mode Exit fullscreen mode

To run this command automatically everyday, all you have to do is to 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('07:00');
}
Enter fullscreen mode Exit fullscreen mode

This will run your command daily at 7am.

In this way you can create a custom command for your application and schedule it to run, or you can set a crontab to run it everyday.

Hope you like my post πŸ˜ƒ πŸ¦„

Thank You. 🦁 🦁

Discussion (0)