Skip to content

SMS

Communication

SMS

Introduction

Text messages reach users who aren't looking at their email, which makes them a good fit for sign-in codes and urgent alerts. The sms package sends text messages through Telnyx in production, and writes them to your log in development.

When you want to reach users on more than one channel, such as an email and a text message about the same paid invoice, send a notification instead. Notifications send their text messages with the configuration on this page.

Configuration

Laravel reads its SMS configuration from these environment variables:

Variable Sets Default
SMS_SENDER The default sender log
SMS_FROM The number, short code, or sender ID that messages come from None
SMS_QUEUE_CONNECTION, SMS_QUEUE Where queued messages go The default queue connection and queue

By default, Laravel uses the log sender so new applications never send real text messages until you configure Telnyx. It logs each recipient at info and the message text at debug. To view message text locally without turning on debug logs everywhere, raise the sms package's log level:

1LOG_LEVEL=info,sms=debug
1LOG_LEVEL=info,sms=debug

Telnyx

Create an API key in the Telnyx portal, then select the telnyx sender:

1SMS_SENDER=telnyx
2SMS_FROM=+15555550100
3TELNYX_KEY=KEY0123
1SMS_SENDER=telnyx
2SMS_FROM=+15555550100
3TELNYX_KEY=KEY0123

Telnyx needs to know which number a message comes from, so set SMS_FROM, TELNYX_MESSAGING_PROFILE_ID, or both. With only a messaging profile, Telnyx picks a number from the profile's number pool.

Send returns once Telnyx accepts a message, but a carrier may still refuse to deliver it. US carriers, for example, block messages from numbers that aren't registered for 10DLC. You'll find those failures in the message's status in the Telnyx portal, not in an error from Send.

Adding senders

If your application needs a second Telnyx account or messaging profile, such as separating on-call alerts from customer messages, add a named sender in your options' Configure function in bootstrap/app.go:

1func configure(cfg *config.Config, env *config.Env) {
2 cfg.SMS.Senders = map[string]config.Telnyx{
3 "alerts": {
4 Key: env.String("TELNYX_ALERTS_KEY", ""),
5 MessagingProfileID: "40017f8e-49bd-4f6a-a7a2-9c1b5d7a2f61",
6 From: "+15555550150",
7 },
8 }
9}
1func configure(cfg *config.Config, env *config.Env) {
2 cfg.SMS.Senders = map[string]config.Telnyx{
3 "alerts": {
4 Key: env.String("TELNYX_ALERTS_KEY", ""),
5 MessagingProfileID: "40017f8e-49bd-4f6a-a7a2-9c1b5d7a2f61",
6 From: "+15555550150",
7 },
8 }
9}

A sender's From number replaces SMS_FROM for its messages, falling back to SMS_FROM when empty. Setting a number on the message itself overrides both.

To send through the alerts sender, name it with sms.Use. It works with Send and Queue:

1err := sms.Use("alerts").To("+15555550123").Send(ctx, "The deploy finished.")
1err := sms.Use("alerts").To("+15555550123").Send(ctx, "The deploy finished.")

Sending messages

To send a text message, pass the recipient's number to sms.To, then pass the request and the text to Send. For example, suppose your application has an Order model and a phone column on users that may be empty. This handler texts the customer when their order ships:

1package orders
2 
3import (
4 "fmt"
5 
6 "go.laravel.com/model"
7 "go.laravel.com/sms"
8 "go.laravel.com/web"
9 
10 "app/models"
11)
12 
13func Ship(r *web.Request) *web.Response {
14 order, err := model.FromRoute[models.Order](r, "order")
15 if err != nil {
16 return web.Fail(err)
17 }
18 
19 customer, err := model.Find[models.User](r, order.UserID)
20 if err != nil {
21 return web.Fail(err)
22 }
23 
24 // Ship the order...
25 
26 if customer.Phone != "" {
27 text := fmt.Sprintf("Order #%d has shipped.", order.ID)
28 if err := sms.To(customer.Phone).Send(r, text); err != nil {
29 return web.Fail(err)
30 }
31 }
32 
33 return web.Back()
34}
1package orders
2 
3import (
4 "fmt"
5 
6 "go.laravel.com/model"
7 "go.laravel.com/sms"
8 "go.laravel.com/web"
9 
10 "app/models"
11)
12 
13func Ship(r *web.Request) *web.Response {
14 order, err := model.FromRoute[models.Order](r, "order")
15 if err != nil {
16 return web.Fail(err)
17 }
18 
19 customer, err := model.Find[models.User](r, order.UserID)
20 if err != nil {
21 return web.Fail(err)
22 }
23 
24 // Ship the order...
25 
26 if customer.Phone != "" {
27 text := fmt.Sprintf("Order #%d has shipped.", order.ID)
28 if err := sms.To(customer.Phone).Send(r, text); err != nil {
29 return web.Fail(err)
30 }
31 }
32 
33 return web.Back()
34}

Send waits for the provider to accept the message. A command, a job, or a listener passes the ctx it received in place of r. To send from a number other than SMS_FROM, call From before Send:

1err := sms.To("+15555550123").From("+15555550199").Send(r, "Your order shipped.")
1err := sms.To("+15555550123").From("+15555550199").Send(r, "Your order shipped.")

Laravel validates the recipient and text before calling Telnyx, so an invalid number or empty message returns an error from Send right away. Messages are not automatically truncated: Telnyx splits long messages into multiple segments and bills per segment (up to 160 characters for GSM text, or 70 characters when emoji or non-GSM characters are included), so keep alerts and verification codes concise.

Phone numbers

Recipient phone numbers must be in E.164 format with a leading + and country code, such as +15555550123. sms.To strips formatting characters such as spaces, dashes, dots, and parentheses, so +1 (555) 555-0123 is valid.

Numbers without a country code, such as 555-0123, fail validation because national numbers are ambiguous across countries, so store user phone numbers in E.164 format when you collect them. sms.Normalize returns a number in that format, or an error, so a handler that saves a user's settings may check the number and tell the user what to fix:

1phone, err := sms.Normalize(form.Phone)
2if err != nil {
3 return web.Invalid(
4 "phone",
5 "Enter your phone number with its country code, such as +1 555 555 0123.",
6 )
7}
1phone, err := sms.Normalize(form.Phone)
2if err != nil {
3 return web.Invalid(
4 "phone",
5 "Enter your phone number with its country code, such as +1 555 555 0123.",
6 )
7}

Queueing messages

Sending SMS synchronously during a request adds external network latency and ties the request's success to Telnyx availability. Call Queue instead to deliver messages through a queue worker with automatic retries on failure. Before calling Queue, you may delay delivery with Delay, or pick a specific queue with OnQueue and a connection with OnConnection:

1err := sms.To("+15555550123").
2 Delay(5*time.Minute).
3 OnQueue("sms").
4 Queue(r, "Your order shipped.")
1err := sms.To("+15555550123").
2 Delay(5*time.Minute).
3 OnQueue("sms").
4 Queue(r, "Your order shipped.")

The job holds the message encrypted with your application key, so you may queue sign-in codes. Like every job, it waits for the current database transaction to commit, and a rollback discards it. A retry doesn't text the customer twice, because every attempt sends Telnyx the same idempotency key.

Testing

You don't want your test suite texting real phones. smstest.New installs a fake in your test's application that records messages instead of sending them, and checks each one as a real send would, so an invalid number still fails the test:

1package feature_test
2 
3import (
4 "fmt"
5 "strings"
6 "testing"
7 
8 "go.laravel.com/model"
9 "go.laravel.com/sms"
10 "go.laravel.com/smstest"
11 
12 "app/models"
13 "app/tests"
14)
15 
16func TestCustomersHearWhenTheirOrderShips(t *testing.T) {
17 client := tests.New(t)
18 texts := smstest.New(client)
19 
20 user := models.User{Name: "Taylor", Email: "[email protected]", Phone: "+15555550123"}
21 if err := model.Create(client.Context(), &user); err != nil {
22 t.Fatal(err)
23 }
24 
25 order := models.Order{UserID: user.ID, Total: 2500}
26 if err := model.Create(client.Context(), &order); err != nil {
27 t.Fatal(err)
28 }
29 
30 page := fmt.Sprintf("/orders/%d", order.ID)
31 client.From(page).Post(page+"/ship", nil).AssertRedirectBack()
32 
33 texts.AssertSent(func(message sms.Message) bool {
34 return message.To == "+15555550123" && strings.Contains(message.Text, "has shipped")
35 })
36}
1package feature_test
2 
3import (
4 "fmt"
5 "strings"
6 "testing"
7 
8 "go.laravel.com/model"
9 "go.laravel.com/sms"
10 "go.laravel.com/smstest"
11 
12 "app/models"
13 "app/tests"
14)
15 
16func TestCustomersHearWhenTheirOrderShips(t *testing.T) {
17 client := tests.New(t)
18 texts := smstest.New(client)
19 
20 user := models.User{Name: "Taylor", Email: "[email protected]", Phone: "+15555550123"}
21 if err := model.Create(client.Context(), &user); err != nil {
22 t.Fatal(err)
23 }
24 
25 order := models.Order{UserID: user.ID, Total: 2500}
26 if err := model.Create(client.Context(), &order); err != nil {
27 t.Fatal(err)
28 }
29 
30 page := fmt.Sprintf("/orders/%d", order.ID)
31 client.From(page).Post(page+"/ship", nil).AssertRedirectBack()
32 
33 texts.AssertSent(func(message sms.Message) bool {
34 return message.To == "+15555550123" && strings.Contains(message.Text, "has shipped")
35 })
36}

The fake counts Send as sent and Queue as queued, and has assertions for each:

Method Asserts or returns
AssertSent(match), AssertQueued(match) A sent, or queued, message matches match
AssertSentTimes(count), AssertQueuedTimes(count) Exactly count messages were sent, or queued
AssertNothingSent() No message was sent or queued
Sent(), Queued() Each sent, or queued, message, in order

AssertSent passes match an sms.Message, with To, From, and Text fields. AssertQueued passes an sms.QueuedMessage, which also has Sender, Connection, Queue, and Delay fields, so you may check where its job would go:

1texts.AssertQueued(func(message sms.QueuedMessage) bool {
2 return message.Queue == "sms" && message.Delay == 5*time.Minute
3})
1texts.AssertQueued(func(message sms.QueuedMessage) bool {
2 return message.Queue == "sms" && message.Delay == 5*time.Minute
3})