One of the more abstract concepts you'll handle when building your business is what the workflow will look like.
At its core, setting up a standardized workflow is about enabling your service providers (agents, hosts, customer service reps, administrators, and the rest of the gang) to better serve your customers.
To illustrate a very real-world example, today we'll build a PHP and Laravel webapp for finding and booking vacation properties — tentatively called Airtng.
Here's how it'll work:
We'll be using the Twilio REST API to send our users messages at important junctures. Here's a bit more on our API:
1<?php23/*4|--------------------------------------------------------------------------5| Web Routes6|--------------------------------------------------------------------------7|8| Here is where you can register web routes for your application. These9| routes are loaded by the RouteServiceProvider within a group which10| contains the "web" middleware group. Now create something great!11|12*/1314Route::get(15'/', ['as' => 'home', function () {16return response()->view('home');17}]18);1920// Session related routes21Route::get(22'/auth/login',23['as' => 'login-index', function () {24return response()->view('login');25}]26);2728Route::get(29'/login',30['as' => 'login-index', function () {31return response()->view('login');32}]33);3435Route::post(36'/login',37['uses' => 'SessionController@login', 'as' => 'login-action']38);3940Route::get(41'/logout',42['as' => 'logout', function () {43Auth::logout();44return redirect()->route('home');45}]46);4748// User related routes49Route::get(50'/user/new',51['as' => 'user-new', function () {52return response()->view('newUser');53}]54);5556Route::post(57'/user/create',58['uses' => 'UserController@createNewUser', 'as' => 'user-create', ]59);6061// Vacation Property related routes62Route::get(63'/property/new',64['as' => 'property-new',65'middleware' => 'auth',66function () {67return response()->view('property.newProperty');68}]69);7071Route::get(72'/properties',73['as' => 'property-index',74'middleware' => 'auth',75'uses' => 'VacationPropertyController@index']76);7778Route::get(79'/property/{id}',80['as' => 'property-show',81'middleware' => 'auth',82'uses' => 'VacationPropertyController@show']83);8485Route::get(86'/property/{id}/edit',87['as' => 'property-edit',88'middleware' => 'auth',89'uses' => 'VacationPropertyController@editForm']90);9192Route::post(93'/property/edit/{id}',94['uses' => 'VacationPropertyController@editProperty',95'middleware' => 'auth',96'as' => 'property-edit-action']97);9899Route::post(100'/property/create',101['uses' => 'VacationPropertyController@createNewProperty',102'middleware' => 'auth',103'as' => 'property-create']104);105106// Reservation related routes107Route::post(108'/property/{id}/reservation/create',109['uses' => 'ReservationController@create',110'as' => 'reservation-create',111'middleware' => 'auth']112);113114Route::post(115'/reservation/incoming',116['uses' => 'ReservationController@acceptReject',117'as' => 'reservation-incoming']118);
Let's boldly go to the next step! Hit the button below to begin.
Our workflow will require allowing users to create accounts and log-in in order to attempt to reserve properties.
Each User
will need to have a phone_number
which will be required to send SMS notifications later.
database/migrations/2014_10_12_000000_create_users_table.php
1<?php23use Illuminate\Database\Schema\Blueprint;4use Illuminate\Database\Migrations\Migration;56class CreateUsersTable extends Migration7{8/**9* Run the migrations.10*11* @return void12*/13public function up()14{15Schema::create('users', function (Blueprint $table) {16$table->increments('id');17$table->string('name');18$table->string('email')->unique();19$table->string('password', 60);20$table->string('phone_number');21$table->string('country_code');22$table->rememberToken();23$table->timestamps();24});25}2627/**28* Reverse the migrations.29*30* @return void31*/32public function down()33{34Schema::drop('users');35}36}
Next up, we will create a table that represents a Vacation Rental property.
We're going to need a way to create the property listings for Airtng to be a success.
The VacationProperty
model belongs to a User
who created it (we'll call this user the host moving forward) and contains only two properties: a description
and an image_url
.
It has two associations: it has many reservations and many users through those reservations.
database/migrations/2015_10_23_193814_create_vacation_properties_table.php
1<?php23use Illuminate\Database\Schema\Blueprint;4use Illuminate\Database\Migrations\Migration;56class CreateVacationPropertiesTable extends Migration7{8/**9* Run the migrations.10*11* @return void12*/13public function up()14{15Schema::create('vacation_properties', function (Blueprint $table) {16$table->increments('id');17$table->integer('user_id')->unsigned();18$table->foreign('user_id')19->references('id')->on('users')20->onDelete('cascade');21$table->string('description');22$table->string('image_url');2324$table->timestamps();25});26}2728/**29* Reverse the migrations.30*31* @return void32*/33public function down()34{35Schema::drop('vacation_properties');36}37}
Next at the plate: how we will model a reservation.
The Reservation
model is at the center of the workflow for this application. It is responsible for keeping track of:
guest
who performed the reservationvacation_property
the guest is requesting (and associated host)status
of the reservation: pending
, confirmed
, or rejected
Since the reservation can only have one guest in this example, we simplified the model by assigning phone_number
directly to the model (but you'll want to move it out).
database/migrations/2015_10_23_194614_create_reservations_table.php
1<?php23use Illuminate\Database\Schema\Blueprint;4use Illuminate\Database\Migrations\Migration;56class CreateReservationsTable extends Migration7{8/**9* Run the migrations.10*11* @return void12*/13public function up()14{15Schema::create('reservations', function (Blueprint $table) {16$table->increments('id');17$table->string('status')18->default('pending');19$table->string('respond_phone_number');20$table->text('message');21$table->integer('vacation_property_id')->unsigned();22$table->foreign('vacation_property_id')23->references('id')->on('vacation_properties')24->onDelete('cascade');25$table->integer('user_id')->unsigned();26$table->foreign('user_id')27->references('id')->on('users')28->onDelete('cascade');2930$table->timestamps();31});32}3334/**35* Reverse the migrations.36*37* @return void38*/39public function down()40{41Schema::drop('reservations');42}43}
Our tables are ready, now let's see how we would create a reservation.
The reservation creation form holds only a single field: the message that will be sent to the host user when reserving one of her properties.
The rest of the information necessary to create a reservation is taken from the user that is logged into the system and the relationship between a property and its owner.
A reservation is created with a default status pending
, so when the host replies with a confirm
or reject
response the system knows which reservation to update.
app/Http/Controllers/ReservationController.php
1<?php2namespace App\Http\Controllers;3use Illuminate\Http\Request;4use App\Http\Requests;5use App\Http\Controllers\Controller;6use Illuminate\Contracts\Auth\Authenticatable;7use App\Reservation;8use App\User;9use App\VacationProperty;10use Twilio\Rest\Client;11use Twilio\TwiML\MessagingResponse;1213class ReservationController extends Controller14{15/**16* Store a new reservation17*18* @param \Illuminate\Http\Request $request19* @return \Illuminate\Http\Response20*/21public function create(Client $client, Request $request, Authenticatable $user, $id)22{23$this->validate(24$request, [25'message' => 'required|string'26]27);28$property = VacationProperty::find($id);29$reservation = new Reservation($request->all());30$reservation->respond_phone_number = $user->fullNumber();31$reservation->user()->associate($property->user);3233$property->reservations()->save($reservation);3435$this->notifyHost($client, $reservation);3637$request->session()->flash(38'status',39"Sending your reservation request now."40);41return redirect()->route('property-show', ['id' => $property->id]);42}4344public function acceptReject(Request $request)45{46$hostNumber = $request->input('From');47$smsInput = strtolower($request->input('Body'));4849$host = User::getUsersByFullNumber($hostNumber)->first();50$reservation = $host->pendingReservations()->first();5152$smsResponse = null;5354if (!is_null($reservation))55{56if (strpos($smsInput, 'yes') !== false || strpos($smsInput, 'accept') !== false)57{58$reservation->confirm();59}60else61{62$reservation->reject();63}6465$smsResponse = 'You have successfully ' . $reservation->status . ' the reservation.';66}67else68{69$smsResponse = 'Sorry, it looks like you don\'t have any reservations to respond to.';70}7172return response($this->respond($smsResponse, $reservation))->header('Content-Type', 'application/xml');73}7475private function respond($smsResponse, $reservation)76{77$response = new MessagingResponse();78$response->message($smsResponse);7980if (!is_null($reservation))81{82$response->message(83'Your reservation has been ' . $reservation->status . '.',84['to' => $reservation->respond_phone_number]85);86}87return $response;88}8990private function notifyHost($client, $reservation)91{92$host = $reservation->property->user;9394$twilioNumber = config('services.twilio')['number'];95$messageBody = $reservation->message . ' - Reply \'yes\' or \'accept\' to confirm the reservation, or anything else to reject it.';9697try {98$client->messages->create(99$host->fullNumber(), // Text any number100[101'from' => $twilioNumber, // From a Twilio number in your account102'body' => $messageBody103]104);105} catch (Exception $e) {106Log::error($e->getMessage());107}108}109}
Let's take a look at how the SMS notification is sent to the host when the reservation is created.
When a reservation is created for a property, we want to notify the owner of that property that someone has requested a reservation.
This is where we use Twilio's Rest API to send an SMS message to the host, using our Twilio phone number. Sending SMS messages using Twilio takes just a few lines of code.
Now we just have to wait for the host to send an SMS response to 'accept' or 'reject', notify the guest, and update the reservation.
app/Http/Controllers/ReservationController.php
1<?php2namespace App\Http\Controllers;3use Illuminate\Http\Request;4use App\Http\Requests;5use App\Http\Controllers\Controller;6use Illuminate\Contracts\Auth\Authenticatable;7use App\Reservation;8use App\User;9use App\VacationProperty;10use Twilio\Rest\Client;11use Twilio\TwiML\MessagingResponse;1213class ReservationController extends Controller14{15/**16* Store a new reservation17*18* @param \Illuminate\Http\Request $request19* @return \Illuminate\Http\Response20*/21public function create(Client $client, Request $request, Authenticatable $user, $id)22{23$this->validate(24$request, [25'message' => 'required|string'26]27);28$property = VacationProperty::find($id);29$reservation = new Reservation($request->all());30$reservation->respond_phone_number = $user->fullNumber();31$reservation->user()->associate($property->user);3233$property->reservations()->save($reservation);3435$this->notifyHost($client, $reservation);3637$request->session()->flash(38'status',39"Sending your reservation request now."40);41return redirect()->route('property-show', ['id' => $property->id]);42}4344public function acceptReject(Request $request)45{46$hostNumber = $request->input('From');47$smsInput = strtolower($request->input('Body'));4849$host = User::getUsersByFullNumber($hostNumber)->first();50$reservation = $host->pendingReservations()->first();5152$smsResponse = null;5354if (!is_null($reservation))55{56if (strpos($smsInput, 'yes') !== false || strpos($smsInput, 'accept') !== false)57{58$reservation->confirm();59}60else61{62$reservation->reject();63}6465$smsResponse = 'You have successfully ' . $reservation->status . ' the reservation.';66}67else68{69$smsResponse = 'Sorry, it looks like you don\'t have any reservations to respond to.';70}7172return response($this->respond($smsResponse, $reservation))->header('Content-Type', 'application/xml');73}7475private function respond($smsResponse, $reservation)76{77$response = new MessagingResponse();78$response->message($smsResponse);7980if (!is_null($reservation))81{82$response->message(83'Your reservation has been ' . $reservation->status . '.',84['to' => $reservation->respond_phone_number]85);86}87return $response;88}8990private function notifyHost($client, $reservation)91{92$host = $reservation->property->user;9394$twilioNumber = config('services.twilio')['number'];95$messageBody = $reservation->message . ' - Reply \'yes\' or \'accept\' to confirm the reservation, or anything else to reject it.';9697try {98$client->messages->create(99$host->fullNumber(), // Text any number100[101'from' => $twilioNumber, // From a Twilio number in your account102'body' => $messageBody103]104);105} catch (Exception $e) {106Log::error($e->getMessage());107}108}109}
Let's see how we would handle incoming messages from Twilio and accept or reject reservations.
We're zoomed in for a closer look at the acceptReject
method. This method handles our incoming Twilio request and does three things:
app/Http/Controllers/ReservationController.php
1<?php2namespace App\Http\Controllers;3use Illuminate\Http\Request;4use App\Http\Requests;5use App\Http\Controllers\Controller;6use Illuminate\Contracts\Auth\Authenticatable;7use App\Reservation;8use App\User;9use App\VacationProperty;10use Twilio\Rest\Client;11use Twilio\TwiML\MessagingResponse;1213class ReservationController extends Controller14{15/**16* Store a new reservation17*18* @param \Illuminate\Http\Request $request19* @return \Illuminate\Http\Response20*/21public function create(Client $client, Request $request, Authenticatable $user, $id)22{23$this->validate(24$request, [25'message' => 'required|string'26]27);28$property = VacationProperty::find($id);29$reservation = new Reservation($request->all());30$reservation->respond_phone_number = $user->fullNumber();31$reservation->user()->associate($property->user);3233$property->reservations()->save($reservation);3435$this->notifyHost($client, $reservation);3637$request->session()->flash(38'status',39"Sending your reservation request now."40);41return redirect()->route('property-show', ['id' => $property->id]);42}4344public function acceptReject(Request $request)45{46$hostNumber = $request->input('From');47$smsInput = strtolower($request->input('Body'));4849$host = User::getUsersByFullNumber($hostNumber)->first();50$reservation = $host->pendingReservations()->first();5152$smsResponse = null;5354if (!is_null($reservation))55{56if (strpos($smsInput, 'yes') !== false || strpos($smsInput, 'accept') !== false)57{58$reservation->confirm();59}60else61{62$reservation->reject();63}6465$smsResponse = 'You have successfully ' . $reservation->status . ' the reservation.';66}67else68{69$smsResponse = 'Sorry, it looks like you don\'t have any reservations to respond to.';70}7172return response($this->respond($smsResponse, $reservation))->header('Content-Type', 'application/xml');73}7475private function respond($smsResponse, $reservation)76{77$response = new MessagingResponse();78$response->message($smsResponse);7980if (!is_null($reservation))81{82$response->message(83'Your reservation has been ' . $reservation->status . '.',84['to' => $reservation->respond_phone_number]85);86}87return $response;88}8990private function notifyHost($client, $reservation)91{92$host = $reservation->property->user;9394$twilioNumber = config('services.twilio')['number'];95$messageBody = $reservation->message . ' - Reply \'yes\' or \'accept\' to confirm the reservation, or anything else to reject it.';9697try {98$client->messages->create(99$host->fullNumber(), // Text any number100[101'from' => $twilioNumber, // From a Twilio number in your account102'body' => $messageBody103]104);105} catch (Exception $e) {106Log::error($e->getMessage());107}108}109}
In order to route an SMS messages to and from the host, we need to setup Twilio webhooks. The next pane will show you the way.
This method handles the Twilio request triggered by the host's SMS and does three things:
In the Twilio console, you should change the 'A Message Comes In' webhook to call your application's endpoint in the route /reservation/incoming:
One way to expose your machine to the world during development is to use ngrok. Your URL for the SMS web hook on your phone number should look something like this:
1http://<subdomain>.ngrok.io/reservation/incoming2
An incoming request from Twilio comes with some helpful parameters. These include the From
phone number and the message Body
.
We'll use the From
parameter to look up the host and check if they have any pending reservations. If they do, we'll use the message body to check for the message 'accepted' or 'rejected'. Finally, we update the reservation status and send an SMS to the guest telling them the host accepted or rejected their reservation request.
In our response to Twilio, we'll use Twilio's TwiML to command Twilio to send an SMS notification message to the host.
app/Http/Controllers/ReservationController.php
1<?php2namespace App\Http\Controllers;3use Illuminate\Http\Request;4use App\Http\Requests;5use App\Http\Controllers\Controller;6use Illuminate\Contracts\Auth\Authenticatable;7use App\Reservation;8use App\User;9use App\VacationProperty;10use Twilio\Rest\Client;11use Twilio\TwiML\MessagingResponse;1213class ReservationController extends Controller14{15/**16* Store a new reservation17*18* @param \Illuminate\Http\Request $request19* @return \Illuminate\Http\Response20*/21public function create(Client $client, Request $request, Authenticatable $user, $id)22{23$this->validate(24$request, [25'message' => 'required|string'26]27);28$property = VacationProperty::find($id);29$reservation = new Reservation($request->all());30$reservation->respond_phone_number = $user->fullNumber();31$reservation->user()->associate($property->user);3233$property->reservations()->save($reservation);3435$this->notifyHost($client, $reservation);3637$request->session()->flash(38'status',39"Sending your reservation request now."40);41return redirect()->route('property-show', ['id' => $property->id]);42}4344public function acceptReject(Request $request)45{46$hostNumber = $request->input('From');47$smsInput = strtolower($request->input('Body'));4849$host = User::getUsersByFullNumber($hostNumber)->first();50$reservation = $host->pendingReservations()->first();5152$smsResponse = null;5354if (!is_null($reservation))55{56if (strpos($smsInput, 'yes') !== false || strpos($smsInput, 'accept') !== false)57{58$reservation->confirm();59}60else61{62$reservation->reject();63}6465$smsResponse = 'You have successfully ' . $reservation->status . ' the reservation.';66}67else68{69$smsResponse = 'Sorry, it looks like you don\'t have any reservations to respond to.';70}7172return response($this->respond($smsResponse, $reservation))->header('Content-Type', 'application/xml');73}7475private function respond($smsResponse, $reservation)76{77$response = new MessagingResponse();78$response->message($smsResponse);7980if (!is_null($reservation))81{82$response->message(83'Your reservation has been ' . $reservation->status . '.',84['to' => $reservation->respond_phone_number]85);86}87return $response;88}8990private function notifyHost($client, $reservation)91{92$host = $reservation->property->user;9394$twilioNumber = config('services.twilio')['number'];95$messageBody = $reservation->message . ' - Reply \'yes\' or \'accept\' to confirm the reservation, or anything else to reject it.';9697try {98$client->messages->create(99$host->fullNumber(), // Text any number100[101'from' => $twilioNumber, // From a Twilio number in your account102'body' => $messageBody103]104);105} catch (Exception $e) {106Log::error($e->getMessage());107}108}109}
In the last step, we'll respond to Twilio's request with some TwiML instructing it to send an SMS to both the host and guest.
After updating the reservation status, we must notify the host that they have successfully confirmed or rejected the reservation. If the host has no pending reservation, we'll instead return an error message.
If we're modifying a reservation, we'll also send a message to the user who requested the rental delivering the happy or sad news.
We use the Message verb from TwiML to instruct Twilio to send two SMS messages.
app/Http/Controllers/ReservationController.php
1<?php2namespace App\Http\Controllers;3use Illuminate\Http\Request;4use App\Http\Requests;5use App\Http\Controllers\Controller;6use Illuminate\Contracts\Auth\Authenticatable;7use App\Reservation;8use App\User;9use App\VacationProperty;10use Twilio\Rest\Client;11use Twilio\TwiML\MessagingResponse;1213class ReservationController extends Controller14{15/**16* Store a new reservation17*18* @param \Illuminate\Http\Request $request19* @return \Illuminate\Http\Response20*/21public function create(Client $client, Request $request, Authenticatable $user, $id)22{23$this->validate(24$request, [25'message' => 'required|string'26]27);28$property = VacationProperty::find($id);29$reservation = new Reservation($request->all());30$reservation->respond_phone_number = $user->fullNumber();31$reservation->user()->associate($property->user);3233$property->reservations()->save($reservation);3435$this->notifyHost($client, $reservation);3637$request->session()->flash(38'status',39"Sending your reservation request now."40);41return redirect()->route('property-show', ['id' => $property->id]);42}4344public function acceptReject(Request $request)45{46$hostNumber = $request->input('From');47$smsInput = strtolower($request->input('Body'));4849$host = User::getUsersByFullNumber($hostNumber)->first();50$reservation = $host->pendingReservations()->first();5152$smsResponse = null;5354if (!is_null($reservation))55{56if (strpos($smsInput, 'yes') !== false || strpos($smsInput, 'accept') !== false)57{58$reservation->confirm();59}60else61{62$reservation->reject();63}6465$smsResponse = 'You have successfully ' . $reservation->status . ' the reservation.';66}67else68{69$smsResponse = 'Sorry, it looks like you don\'t have any reservations to respond to.';70}7172return response($this->respond($smsResponse, $reservation))->header('Content-Type', 'application/xml');73}7475private function respond($smsResponse, $reservation)76{77$response = new MessagingResponse();78$response->message($smsResponse);7980if (!is_null($reservation))81{82$response->message(83'Your reservation has been ' . $reservation->status . '.',84['to' => $reservation->respond_phone_number]85);86}87return $response;88}8990private function notifyHost($client, $reservation)91{92$host = $reservation->property->user;9394$twilioNumber = config('services.twilio')['number'];95$messageBody = $reservation->message . ' - Reply \'yes\' or \'accept\' to confirm the reservation, or anything else to reject it.';9697try {98$client->messages->create(99$host->fullNumber(), // Text any number100[101'from' => $twilioNumber, // From a Twilio number in your account102'body' => $messageBody103]104);105} catch (Exception $e) {106Log::error($e->getMessage());107}108}109}
Congratulations! We've just automated a rental workflow with Twilio's Programmable SMS, and now you're ready to add it to your own application.
Next, let's take a look at some other features you might like to add.
PHP + Twilio? Excellent choice! Here are a couple other tutorials for you to try:
Put a button on your web page that connects visitors to live support or salespeople via telephone.
Instantly collect structured data from your users with a survey conducted over a voice call or SMS text messages.