Level up your Twilio API skills in TwilioQuest, an educational game for Mac, Windows, and Linux. Download Now


Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

SMS and MMS Marketing Notifications with PHP and Laravel

Ready to implement SMS and MMS marketing notifications? Because of the high read-rate and the always-present nature of mobile devices, marketing through SMS is an excellent choice. Today we'll build notifications with PHP and Laravel.


  1. A potential customer sends an SMS to a Twilio phone number you've advertised somewhere
  2. Your application confirms that the user wants to receive SMS and MMS notifications from you
  3. An administrator crafts a message in a web form to send to all subscribers

Walmartが「Value of the day」販促キャンペーンの一環として顧客に特売情報を毎日送信した方法をご覧ください。

Basic Twilio building blocks

For this tutorial we'll be working with the following tools:

  • TwiML and the <Message> Verb: We'll use TwiML, the Twilio Markup Lamguage to manage interactions initiated by the user via SMS.
  • Messages Resource: We will use the Twilio REST API to send marketing messages out to all subscribers.

さぁ、はじめましょう! 下のボタンをクリックして、チュートリアルの次の手順に移動してください。

I'm in - let's begin

Making the Subscriber class

In order to track who wants our marketing messages, let's start at the beginning and provide the right model:

  • phone_number stores where to send the marketing messages.
  • subscribed is a boolean which tracks if a Subscriber is opted in. Unsubscribed users will not receive messages.

We can use the command line to create the scaffolding for this model with a command similar to:

php artisan make:model Subscriber -m
        How we will store details about our subscribers.

        The Subscriber Model

        How we will store details about our subscribers.

        Now that we have a model, let's create the migration.

        Sweet! Let's migrate our database.

        Create a migration for the Subscriber model

        To create the table where we’ll store subscriber info, we’ll create a migration and then execute it. First, create a basic migration file by running the command:

        php artisan make:migration subscribers

        Next, open the new file and add info on the fields we need this table to have. It will be located in the database/migrations directory and named with the current timestamp and the table name we provide. For example, it might look something like 2018_02_01_012345_create_subscribers_table.php

        Inside the file we’ll find the class CreateSubscribersTable which contains two methods: up() and down() for creating or destroying our table. We just need to edit the up() method to add the phone_number and subscribed fields we need for our model.

        Here's how the migration should look:

              Your migration should contain the information we need to store for the Subscriber model we just made.

              The Subscriber Migration

              Your migration should contain the information we need to store for the Subscriber model we just made.

              To create that table in our database, our database name, database user, and database password will need to be setup to match the local database installation in our Laravel project’s .env file.

              Next, run the command:

              php artisan migrate

              ... and the migration should be successful.

              Simple, right? Next let's look at how to handle incoming messages from people opting into the service.

              See how to handle incoming message

              Handling incoming text messages in PHP and Laravel

              Here we create the endpoint that Twilio calls every time our number receives an incoming message from a new subscriber.

              It relies on a createMessage method that produces the message that will be returned, resulting in a warm and fuzzy welcome message.


                    Method to register a new subscriber


                    Next we'll show how the createMessage method works.

                    Zoom Into createMessage

                    Create a subscriber from an incoming message

                    We begin by getting the user's phone number from the incoming Twilio request. Then we try to find a Subscriber with that phone number.

                    If there's no subscriber with this phone number, we create one, save it, and respond with a message asking them to text the word "add". By default, users won't be subscribed; users will need to confirm the subscription with an additional text.

                          Register a new Subscriber if its phone number is not already in the database

                          Handle incoming messages with Laravel

                          Register a new Subscriber if its phone number is not already in the database

                          To recap: we've created a Subscriber model to keep track of the people that want our messages, and need to implement subscribing and opting-out.

                          Let's look at the subscribe/unsubscribe logic on the next pane.

                          Zoom in on the Business Logic

                          Manage user subscriptions

                          ユーザーの購読状態の管理に、addremove という2つのSMSコマンドを提供することにします。 

                          These commands will toggle a boolean flag for a Subscriber record in the database and will control that customer's marketing message preference.

                          To make this happen, the controller logic handles incoming messages from known Subscribers like this:

                          • それが add または remove コマンドの場合は、データベースで適切なステータスを使用して購読を作成/更新します。
                          • それが認識できないコマンドの場合は、使用可能なコマンドについて説明するメッセージを送信します。

                                Validate and apply an incoming subscriber command


                                We'll visit the message creation form next.

                                Let's Make Some Messages

                                Set up the business logic for marketing messages

                                From the site's frontend, we retrieve the message text (and/or image URL) first. Next we loop through all subscribers and call the sendMessage method to send the message out.

                                When the messages are on their way, we redirect the submitter back to the notifications.create route with a Flash Data message containing feedback about the messaging attempt.


                                      Webhook to send a message to all active subscribers


                                      Ready to see how we send SMS and MMS messages themselves?

                                      How Do You Send Out the Actual Messages?

                                      Send SMS or MMS marketing messages

                                      In the method sendMessage we create a Twilio REST API client that can be used to send either SMS or MMS messages.

                                      The client requires your Twilio account credentials (an Account SID and Auth Token), which can be found in the Twilio Console:


                                      You'll want to set those in the .env file. (Additionally, you'll need to add a SMS-capable number there from the Phone Number console.) Once the app is running, then all we need to do is call create on the client->messages object in order to send our message.

                                      The Twilio Message API call requires a to parameter and an array containing a from number, the message body and an optional mediaUrl.


                                            Use the Twilio PHP client to send a message


                                            And with that, the application is completely wired. Next up, we'll look at what other features we can easily add with Twilio and a little guidance from our tutorials.


                                            一丁あがり! SMS および MMS マーケティングキャンペーンを実行するためのオプトインプロセスと管理インターフェイスを実装しました。

                                            Now all you need is some killer content to share with your users via text or MMS (That's for you to find!).

                                            PHP and Twilio are a great mix. Here are just a couple of other features we think you'll enjoy:

                                            IVR: フォンツリー

                                            IVR(interactive voice response:自動音声応答)システムで、発信者を適切な担当者および情報に簡単にルーティングできます。


                                            音声通話または SMS テキストメッセージを介して調査を実施し、ユーザーから構造化データを迅速に収集します。


                                            If you have any feedback to share with us please tweet to us @twilio. We love to hear what you've built and what you're building!

                                            Mario Celi Agustin Camino Paul Kamp Andrew Baker David Prothero Kat King
                                            Rate this page:


                                            誰しもが一度は考える「コーディングって難しい」。そんな時は、お問い合わせフォームから質問してください。 または、Stack Overflow でTwilioタグのついた情報から欲しいものを探してみましょう。