How to Send Daily SMS Reminders in PHP 7 Laravel Web Apps with cron

October 04, 2019
Written by
Matt Makai
Twilion

How to Send Daily SMS Reminders in PHP 7 Laravel Web Apps with Cron

Sending and receiving SMS is easy with the Twilio API, but what if you want to send regularly-scheduled reminders from your Laravel web applications? In this tutorial, we'll combine Laravel, Twilio Programmable SMS and cron to send daily reminders that are stored in a Laravel data model.

Project Dependencies

We'll need the following dependencies to complete this tutorial:

We can start building our project once you have PHP 7 and Composer installed. We'll sign up for a Twilio account at the appropriate step in the tutorial.

All of the code for the project can be found within this Git repository on GitHub.

Create a Laravel Project with Composer and the Twilio Helper Library

In your terminal, start a new Laravel project named reminder-app using the following command:

$ composer create-project laravel/laravel reminder-app

You should see a bunch of standard Composer output that ends with the following three lines:

Package manifest generated successfully.
> @php artisan key:generate --ansi
Application key set successfully.

Change into the reminder-app directory:

$ cd reminder-app

Install the Twilio PHP helper library. This library will help us to connect to the Twilio API directly from our application.

$ composer require twilio/sdk

When Composer is finished installing the Twilio PHP helper library package you should see output similar to this:

Using version ^5.36 for twilio/sdk
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing twilio/sdk (5.36.0): Downloading (100%)         
twilio/sdk suggests installing guzzlehttp/guzzle (An HTTP client to execute the API requests)
Writing lock file
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: beyondcode/laravel-dump-server
Discovered Package: fideloper/proxy
Discovered Package: laravel/tinker
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Package manifest generated successfully.

Next, we will sign up for Twilio and populate a few environment variables.

Obtaining Our Twilio Credentials

Head over to twilio.com and sign up for an account if you do not already have one. After the registration process, take a look at your account credentials on the Twilio Console.

Twilio Account Number Dashboard

Use the phone number that comes with your trial account or purchase a new phone number to use for this project. Set the Twilio phone number as the TWILIO_PHONE_NUMBER environment variable and the phone number you want to send the reminder to as TO_NUMBER.

TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxx  # found on Twilio.com/console
TWILIO_AUTH_TOKEN=yyyyyyyyyyyyyyy  # found on Twilio.com/console
TWILIO_PHONE_NUMBER=+12029026420  # your Twilio number                             
TO_NUMBER=+14155550909  # the number to send reminders to

It's time to write some PHP code for our reminders application.

Creating the Laravel Model with Artisan

Run the following command to create the model to store our reminders:

$ php artisan make:model Reminder

You should see Model created successfully. as the output. The command created a new file named Reminder.php within the app directory.

Open the app/Reminder.php file and add the following new method to the class.


<?php                                                                                                              

namespace App;

use Illuminate\Database\Eloquent\Model;
use Twilio\Rest\Client;

class Reminder extends Model
{
    /**
    * send Twilio SMS
    *
    * @param $to
    * @param $sms_body
    */
    function sendSMS( $to, $sms_body ) {
        // Your Account SID and Auth Token from twilio.com/console
        $sid    = getenv( 'TWILIO_ACCOUNT_SID' );
        $token  = getenv( 'TWILIO_AUTH_TOKEN' );
        $client = new Client( $sid, $token );
        $client->messages->create(
             $to,
             [
             // A Twilio phone number you purchased at twilio.com/console
             'from' => getenv( 'TWILIO_PHONE_NUMBER' ),
             // the body of the text message you'd like to send
             'body' => $sms_body
             ]
        );
    }
}

The above sendSMS method imports your Twilio credentials from the environment variables TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN. It then uses them to instantiate the Twilio PHP helper library client and send an SMS to the phone number specified in the TWILIO_PHONE_NUMBER environment variable.

Next we need a method that calls sendSMS and specifies the phone number to send the reminder to, as well as what message to send. Add the following highlighted lines to app/Reminder.php.


<?php                                                                              

namespace App;

use Illuminate\Database\Eloquent\Model;
use Twilio\Rest\Client;

class Reminder extends Model
{
    /**
    * send Twilio SMS
    *
    * @param $to
    * @param $sms_body
    */
    function sendSMS( $to, $sms_body ) {
        // Your Account SID and Auth Token from twilio.com/console
        $sid    = getenv( 'TWILIO_ACCOUNT_SID' );
        $token  = getenv( 'TWILIO_AUTH_TOKEN' );
        $client = new Client( $sid, $token );
        $client->messages->create(
             $to,
             [
             // A Twilio phone number you purchased at twilio.com/console
             'from' => getenv( 'TWILIO_PHONE_NUMBER' ),
             // the body of the text message you'd like to send
             'body' => $sms_body
             ]
        );
    }


    public function sendReminders() {
        // Fill in a reminder you'd like to send in this function, either populated
        //  by a constant or from the database.
        $reminder = "This is your daily reminder. Get it done!";
        $recipients = [
            [ 'to' => getenv('TO_NUMBER') ]
            // add additional recipients here, if necessary
        ];
        foreach($recipients as $recipient) {
            $this->sendSMS($recipient['to'], $reminder);
        }
    }
}

The above code only has a single number listed under the recipients variable, but you can add as many as you would like to the array. The code loops through each element in the array and invokes the sendSMS method with the number that needs the reminder and the message to send.

We need a way to test our code and easily call it with a command on the command line. Make sure app/Reminder.php is saved, then go back to the base directory of your project. Use the following artisan command to generate the boilerplate code to create a new Laravel command for this project:

$ php artisan make:command sendReminders

The above code created a new file under the app/Console/Commands/ directory named sendReminders.php. Open that file and add the following highlighted lines.


<?php                                                                                 

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Reminder;

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

    /** 
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send reminder(s) via SMS using Twilio.';

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

    /** 
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {   
        $reminder=new Reminder();
        $reminder->sendReminders();
        $this->info('Success! Check your messages.');
    }   
}

The new lines of code call the app/Reminder.php code that we previously wrote. Let's give our application a try.

Testing Our Reminders Laravel App

Make sure the app/Console/Commands/sendReminders.php file is saved, then execute this artisan command.

$ php artisan send:reminder

You should see:

Success! Check your messages.

And on the phone with the number you set as your TO_NUMBER:

iMessage screen

That'll do it. The code works! We just need a cron job to kick off the reminder each day.

Sending Daily SMS Reminders with PHP and Chronos (cron)

We’ll need a bit more PHP, as well as a cron job to execute our code on a regular basis so the messages are sent daily. If you've never used cron before, this tutorial is great for understanding the basics.

Open the app/Console/Kernel.php file and update it with the following highlighted lines of code:


<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /** 
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [ 
        //  
    ];  

    /** 
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {  
        $schedule->command('send:reminder')->dailyAt('6:00');                                                              
    }

    /** 
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {   
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

The above line of code schedules the send:reminder command to run each day at 6am, but we still need a cron job to initiate the command schedule. Add a new command to cron with this command:

$ crontab -e

The cron configuration file will open in your default text editor. Now add this line to the configuration:

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

This cron job will call the Laravel scheduler and run the tasks that are due for execution.

Wrapping up Our PHP Reminders Application

We just created an application to send daily text messages with one or more reminders of our choice. The web app is built with Laravel which minimized the amount of custom code we needed to get the job done.

That is it for this tutorial, but there are many ways to expand your application. Next, you should view Twilio's PHP Voices page, which contains the latest and greatest PHP tutorials we’ve published. 

Here are a few great tutorials on there that you can build next or add to this reminders app:

That's all for now, happy coding and we can't wait to see what you build next!