Skip to contentSkip to navigationSkip to topbar
On this page

Send Appointment Reminders with PHP and Laravel


(information)

Info

Ahoy! We now recommend you build your appointment reminders with Twilio's built-in Message Scheduling functionality. Head on over to the Message Scheduling documentation to learn more about scheduling messages.

This Laravel 5(link takes you to an external page) web application shows how to create appointments for customers at a date in future, and send out reminders for those appointments in a background job(link takes you to an external page) that runs every few minutes.

In this tutorial, we'll point out the key bits of code that make this application work. Check out the project README on GitHub(link takes you to an external page) to see how to run the code yourself.

Check out how Yelp uses SMS to confirm restaurant reservations for diners.(link takes you to an external page)

Let's get started! Click the button below to begin.


Configure the application to use Twilio

configure-the-application-to-use-twilio page anchor

Before we can use the Twilio API to send reminder text messages, we need to configure our account credentials. These can be found on your Twilio Console. You'll also need an SMS-enabled phone number - you can find or purchase a new one to use here.

We configure these values using Dotenv(link takes you to an external page), the configuration library of choice for Laravel applications. More information on how to configure this application can be found in the project README(link takes you to an external page).

Configure the application

configure-the-application page anchor

.env.example

1
APP_ENV=local
2
APP_DEBUG=true
3
APP_KEY=ufxhZiQcKxi1eHVmGq8MwfAcRgZHJ1Qq
4
5
DB_HOST=localhost
6
DB_DATABASE=appointments
7
DB_USERNAME=appointments
8
DB_PASSWORD=appointments
9
10
# Twilio API credentials
11
# Found at https://www.twilio.com/user/account/settings
12
TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXXXXX
13
TWILIO_AUTH_TOKEN=your_token
14
15
# Twilio phone number
16
# Purchase one at https://www.twilio.com/user/account/phone-numbers/incoming
17
TWILIO_NUMBER=your_twilio_number

Next let's see how we create a new Appointment.


Create a new appointment

create-a-new-appointment page anchor

In order to send an appointment reminder, we first need to create an appointment! In the controller(link takes you to an external page), we take information submitted in a form(link takes you to an external page) (notably a customer's name and phone number, plus a time for the appointment in the future) and save it in an Appointment model.

We use the Carbon date library(link takes you to an external page) to parse and do operations with the time.

app/Http/Controllers/AppointmentController.php

1
<?php
2
3
namespace App\Http\Controllers;
4
5
use Illuminate\Http\Request;
6
use Illuminate\Http\Response;
7
use Carbon\Carbon;
8
9
use App\Http\Requests;
10
use App\Http\Controllers\Controller;
11
12
class AppointmentController extends Controller
13
{
14
private $appointment;
15
private $validInputConditions = array(
16
'name' => 'required',
17
'phoneNumber' => 'required|min:5',
18
'when' => 'required',
19
'timezoneOffset' => 'required',
20
'delta' => 'required|numeric'
21
);
22
23
/**
24
* Display a listing of the resource.
25
*
26
* @return Response
27
*/
28
public function index()
29
{
30
$allAppointments = \App\Appointment::orderBy('id', 'ASC')->get();
31
return response()->view('appointment.index', array('apts' => $allAppointments));
32
}
33
34
/**
35
* Show the form for creating a new resource.
36
*
37
* @return Response
38
*/
39
public function create()
40
{
41
$appointment = new \App\Appointment;
42
return \View::make('appointment.create', array('appointment' => $appointment));
43
}
44
45
/**
46
* Store a newly created resource in storage.
47
*
48
* @return Response
49
*/
50
public function store(Request $request)
51
{
52
$newAppointment = $this->appointmentFromRequest($request);
53
$newAppointment->save();
54
return redirect()->route('appointment.index');
55
}
56
57
/**
58
* Delete a resource in storage.
59
*
60
* @return Response
61
*/
62
public function destroy($id) {
63
\App\Appointment::find($id)->delete();
64
return redirect()->route('appointment.index');
65
}
66
67
public function edit($id) {
68
$appointmentToEdit = \App\Appointment::find($id);
69
return \View::make('appointment.edit', array('appointment' => $appointmentToEdit));
70
}
71
72
public function update(Request $request, $id) {
73
$updatedAppointment = $this->appointmentFromRequest($request);
74
$existingAppointment = \App\Appointment::find($id);
75
76
$existingAppointment->name = $updatedAppointment->name;
77
$existingAppointment->phoneNumber = $updatedAppointment->phoneNumber;
78
$existingAppointment->timezoneOffset = $updatedAppointment->timezoneOffset;
79
$existingAppointment->when = $updatedAppointment->when;
80
$existingAppointment->notificationTime = $updatedAppointment->notificationTime;
81
82
$existingAppointment->save();
83
return redirect()->route('appointment.index');
84
}
85
86
private function appointmentFromRequest(Request $request) {
87
$this->validate($request, $this->validInputConditions);
88
$newAppointment = new \App\Appointment;
89
90
$newAppointment->name = $request->input('name');
91
$newAppointment->phoneNumber = $request->input('phoneNumber');
92
$newAppointment->timezoneOffset = $request->input('timezoneOffset');
93
$newAppointment->when = $request->input('when');
94
95
$notificationTime = Carbon::parse($request->input('when'))->subMinutes($request->delta);
96
$newAppointment->notificationTime = $notificationTime;
97
98
return $newAppointment;
99
}
100
}

Now that we have our Appointment created, let's see how to schedule a reminder for it.


Schedule a job to send reminders

schedule-a-job-to-send-reminders page anchor

Every ten minutes, we'd like our application to check the appointments database to see if any appointments are coming up that require reminders to be sent out. We configure both the job code we'd like to run and the interval on which to run it here.

Schedule a job to send reminders

schedule-a-job-to-send-reminders-1 page anchor

app/Console/Kernel.php

1
<?php
2
3
namespace App\Console;
4
5
use Illuminate\Console\Scheduling\Schedule;
6
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
7
8
class Kernel extends ConsoleKernel
9
{
10
/**
11
* The Artisan commands provided by your application.
12
*
13
* @var array
14
*/
15
protected $commands = [
16
'\App\Console\Commands\SendReminders'
17
];
18
19
/**
20
* Define the application's command schedule.
21
*
22
* @param \Illuminate\Console\Scheduling\Schedule $schedule
23
* @return void
24
*/
25
protected function schedule(Schedule $schedule)
26
{
27
$schedule->command('reminders:send')->everyMinute();
28
}
29
30
/**
31
* Register the commands for the application.
32
*
33
* @return void
34
*/
35
protected function commands()
36
{
37
$this->load(__DIR__.'/Commands');
38
39
require base_path('routes/console.php');
40
}
41
}

With our job configured, we're now ready to write the actual console command code that will send out our reminders.


Create a console command to run the job

create-a-console-command-to-run-the-job page anchor

To actually execute our recurring job logic, we create an Artisan console command(link takes you to an external page) which queries the database for upcoming appointments and sends reminders as necessary. As an added bonus, defining our job logic in this way allows us to run the reminder job whenever we want from the command line.

Create a console command to run the job

create-a-console-command-to-run-the-job-1 page anchor

app/Console/Commands/SendReminders.php

1
<?php
2
3
namespace App\Console\Commands;
4
5
use Illuminate\Console\Command;
6
7
class SendReminders extends Command
8
{
9
/**
10
* The name and signature of the console command.
11
*
12
* @var string
13
*/
14
protected $signature = 'reminders:send';
15
16
/**
17
* The console command description.
18
*
19
* @var string
20
*/
21
protected $description = 'Send reminders using Twilio';
22
23
/**
24
* Create a new command instance.
25
*
26
* @return void
27
*/
28
public function __construct()
29
{
30
parent::__construct();
31
}
32
33
/**
34
* Execute the console command.
35
*
36
* @return void
37
*/
38
public function handle()
39
{
40
$appointmentReminder = new \App\AppointmentReminders\AppointmentReminder();
41
$appointmentReminder->sendReminders();
42
}
43
}

Let's dig further into the ApplicationReminder class


Find appointments that need reminders

find-appointments-that-need-reminders page anchor

Our recurring job uses an instance of the AppointmentReminder class to query the database for appointments coming up in the next ten minutes and send out reminder messages.

In the constructor, we execute the database query using a custom scope(link takes you to an external page) on the Appointment model. This should give us a list of all appointments with a date and time that falls within the next ten minutes.

Find appointments that need reminders

find-appointments-that-need-reminders-1 page anchor

app/AppointmentReminders/AppointmentReminder.php

1
<?php
2
3
namespace App\AppointmentReminders;
4
5
use Illuminate\Log;
6
use Carbon\Carbon;
7
use Twilio\Rest\Client;
8
9
class AppointmentReminder
10
{
11
/**
12
* Construct a new AppointmentReminder
13
*
14
* @param Illuminate\Support\Collection $twilioClient The client to use to query the API
15
*/
16
function __construct()
17
{
18
$this->appointments = \App\Appointment::appointmentsDue()->get();
19
20
$twilioConfig =\Config::get('services.twilio');
21
$accountSid = $twilioConfig['twilio_account_sid'];
22
$authToken = $twilioConfig['twilio_auth_token'];
23
$this->sendingNumber = $twilioConfig['twilio_number'];
24
25
$this->twilioClient = new Client($accountSid, $authToken);
26
}
27
28
/**
29
* Send reminders for each appointment
30
*
31
* @return void
32
*/
33
public function sendReminders()
34
{
35
$this->appointments->each(
36
function ($appointment) {
37
$this->_remindAbout($appointment);
38
}
39
);
40
}
41
42
/**
43
* Sends a message for an appointment
44
*
45
* @param Appointment $appointment The appointment to remind
46
*
47
* @return void
48
*/
49
private function _remindAbout($appointment)
50
{
51
$recipientName = $appointment->name;
52
$time = Carbon::parse($appointment->when, 'UTC')
53
->subMinutes($appointment->timezoneOffset)
54
->format('g:i a');
55
56
$message = "Hello $recipientName, this is a reminder that you have an appointment at $time!";
57
$this->_sendMessage($appointment->phoneNumber, $message);
58
}
59
60
/**
61
* Sends a single message using the app's global configuration
62
*
63
* @param string $number The number to message
64
* @param string $content The content of the message
65
*
66
* @return void
67
*/
68
private function _sendMessage($number, $content)
69
{
70
$this->twilioClient->messages->create(
71
$number,
72
array(
73
"from" => $this->sendingNumber,
74
"body" => $content
75
)
76
);
77
}
78
}

Now let's setup the Twilio REST Client in order to send some SMS reminder messages.


Set up a Twilio API client

set-up-a-twilio-api-client page anchor

Also in the AppointmentReminder constructor, we create a Twilio REST Client to send out reminders via SMS. We initialize it with the Twilio account credentials we configured earlier.

app/AppointmentReminders/AppointmentReminder.php

1
<?php
2
3
namespace App\AppointmentReminders;
4
5
use Illuminate\Log;
6
use Carbon\Carbon;
7
use Twilio\Rest\Client;
8
9
class AppointmentReminder
10
{
11
/**
12
* Construct a new AppointmentReminder
13
*
14
* @param Illuminate\Support\Collection $twilioClient The client to use to query the API
15
*/
16
function __construct()
17
{
18
$this->appointments = \App\Appointment::appointmentsDue()->get();
19
20
$twilioConfig =\Config::get('services.twilio');
21
$accountSid = $twilioConfig['twilio_account_sid'];
22
$authToken = $twilioConfig['twilio_auth_token'];
23
$this->sendingNumber = $twilioConfig['twilio_number'];
24
25
$this->twilioClient = new Client($accountSid, $authToken);
26
}
27
28
/**
29
* Send reminders for each appointment
30
*
31
* @return void
32
*/
33
public function sendReminders()
34
{
35
$this->appointments->each(
36
function ($appointment) {
37
$this->_remindAbout($appointment);
38
}
39
);
40
}
41
42
/**
43
* Sends a message for an appointment
44
*
45
* @param Appointment $appointment The appointment to remind
46
*
47
* @return void
48
*/
49
private function _remindAbout($appointment)
50
{
51
$recipientName = $appointment->name;
52
$time = Carbon::parse($appointment->when, 'UTC')
53
->subMinutes($appointment->timezoneOffset)
54
->format('g:i a');
55
56
$message = "Hello $recipientName, this is a reminder that you have an appointment at $time!";
57
$this->_sendMessage($appointment->phoneNumber, $message);
58
}
59
60
/**
61
* Sends a single message using the app's global configuration
62
*
63
* @param string $number The number to message
64
* @param string $content The content of the message
65
*
66
* @return void
67
*/
68
private function _sendMessage($number, $content)
69
{
70
$this->twilioClient->messages->create(
71
$number,
72
array(
73
"from" => $this->sendingNumber,
74
"body" => $content
75
)
76
);
77
}
78
}

With the client and the reminders in hand. All that is left is to send an SMS for them.


Send reminder messages with the Twilio API

send-reminder-messages-with-the-twilio-api page anchor

These two private functions are called for every appointment coming up that requires a reminder to be sent. The first formats the text of the message to be sent out. The second actually uses the Twilio REST API client to send out a text message.

We provide a to parameter which is the customer's phone number, a from parameter which is a number in our account, and a body parameter which contains the text of the message.

Send reminder messages with the Twilio API

send-reminder-messages-with-the-twilio-api-1 page anchor

app/AppointmentReminders/AppointmentReminder.php

1
<?php
2
3
namespace App\AppointmentReminders;
4
5
use Illuminate\Log;
6
use Carbon\Carbon;
7
use Twilio\Rest\Client;
8
9
class AppointmentReminder
10
{
11
/**
12
* Construct a new AppointmentReminder
13
*
14
* @param Illuminate\Support\Collection $twilioClient The client to use to query the API
15
*/
16
function __construct()
17
{
18
$this->appointments = \App\Appointment::appointmentsDue()->get();
19
20
$twilioConfig =\Config::get('services.twilio');
21
$accountSid = $twilioConfig['twilio_account_sid'];
22
$authToken = $twilioConfig['twilio_auth_token'];
23
$this->sendingNumber = $twilioConfig['twilio_number'];
24
25
$this->twilioClient = new Client($accountSid, $authToken);
26
}
27
28
/**
29
* Send reminders for each appointment
30
*
31
* @return void
32
*/
33
public function sendReminders()
34
{
35
$this->appointments->each(
36
function ($appointment) {
37
$this->_remindAbout($appointment);
38
}
39
);
40
}
41
42
/**
43
* Sends a message for an appointment
44
*
45
* @param Appointment $appointment The appointment to remind
46
*
47
* @return void
48
*/
49
private function _remindAbout($appointment)
50
{
51
$recipientName = $appointment->name;
52
$time = Carbon::parse($appointment->when, 'UTC')
53
->subMinutes($appointment->timezoneOffset)
54
->format('g:i a');
55
56
$message = "Hello $recipientName, this is a reminder that you have an appointment at $time!";
57
$this->_sendMessage($appointment->phoneNumber, $message);
58
}
59
60
/**
61
* Sends a single message using the app's global configuration
62
*
63
* @param string $number The number to message
64
* @param string $content The content of the message
65
*
66
* @return void
67
*/
68
private function _sendMessage($number, $content)
69
{
70
$this->twilioClient->messages->create(
71
$number,
72
array(
73
"from" => $this->sendingNumber,
74
"body" => $content
75
)
76
);
77
}
78
}

That's it! Our Laravel application is all set to send out reminders for upcoming appointments.


We hope you found this sample application useful. If you're a PHP developer working with Twilio, you might enjoy these other tutorials:

Click to Call

Put a button on your web page that connects visitors to live support or sales people via telephone.

Two-Factor Authentication

Improve the security of Laravel's built-in login functionality by adding two-factor authentication via text message.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.