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 laravel::sms module 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 body at debug. To view message bodies locally, such as sign-in codes during development, raise the log level for SMS:
1LOG_LEVEL=info,laravel::sms=debug1LOG_LEVEL=info,laravel::sms=debug
Telnyx
Create an API key in the Telnyx portal, then select the telnyx sender:
1SMS_SENDER=telnyx2SMS_FROM=+155555501003TELNYX_KEY=KEY01231SMS_SENDER=telnyx2SMS_FROM=+155555501003TELNYX_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, register a named sender in src/app.rs:
1use laravel::config::sms::Telnyx;23Application::configure()4 .with_config(|config, env| {5 let key: String = env.get("TELNYX_ALERTS_KEY").unwrap_or_default();67 config.sms.add_sender(8 "alerts",9 Telnyx::new(key)10 .messaging_profile_id("40017f8e-49bd-4f6a-a7a2-9c1b5d7a2f61")11 .from("+15555550150"),12 );13 })1use laravel::config::sms::Telnyx;23Application::configure()4 .with_config(|config, env| {5 let key: String = env.get("TELNYX_ALERTS_KEY").unwrap_or_default();67 config.sms.add_sender(8 "alerts",9 Telnyx::new(key)10 .messaging_profile_id("40017f8e-49bd-4f6a-a7a2-9c1b5d7a2f61")11 .from("+15555550150"),12 );13 })
A sender's from number replaces SMS_FROM for its messages, falling back to SMS_FROM when unset. Setting a number on the message itself overrides both.
To send through the alerts sender, name it with sender. It works with send and queue:
1use laravel::sms;23sms::to("+15555550123").sender("alerts").send("The deploy finished.").await?;1use laravel::sms;23sms::to("+15555550123").sender("alerts").send("The deploy finished.").await?;
Sending messages
To send a text message, pass the recipient's number to sms::to and the body to send. For example, suppose your application has an Order model and a nullable phone column on users:
1use laravel::prelude::*;2use laravel::sms;34pub async fn ship(Params(id): Params<i64>) -> laravel::Result<Redirect> {5 let order = Order::find_or_fail(id).await?;6 let customer = User::find_or_fail(order.user_id).await?;78 // Ship the order...910 if let Some(phone) = &customer.phone {11 sms::to(phone).send(format!("Order #{} has shipped.", order.id)).await?;12 }1314 Ok(Redirect::back())15}1use laravel::prelude::*;2use laravel::sms;34pub async fn ship(Params(id): Params<i64>) -> laravel::Result<Redirect> {5 let order = Order::find_or_fail(id).await?;6 let customer = User::find_or_fail(order.user_id).await?;78 // Ship the order...910 if let Some(phone) = &customer.phone {11 sms::to(phone).send(format!("Order #{} has shipped.", order.id)).await?;12 }1314 Ok(Redirect::back())15}
send waits for the provider to accept the message. To send from a number other than SMS_FROM, pass an sms::Message:
1use laravel::sms::{self, Message};23sms::to("+15555550123")4 .send(Message::new("Your order shipped.").from("+15555550199"))5 .await?;1use laravel::sms::{self, Message};23sms::to("+15555550123")4 .send(Message::new("Your order shipped.").from("+15555550199"))5 .await?;
Laravel validates the recipient and body before calling Telnyx, so an invalid number or empty message fails immediately at the send call. 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 accepts &str, String, or PhoneNumber and 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 collected.
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 awaiting, you may delay delivery or pick a specific queue:
1use laravel::sms;2use laravel::time::ToSpan;34sms::to("+15555550123")5 .queue("Your order shipped.")6 .delay(5.minutes())7 .on_queue("sms")8 .await?;1use laravel::sms;2use laravel::time::ToSpan;34sms::to("+15555550123")5 .queue("Your order shipped.")6 .delay(5.minutes())7 .on_queue("sms")8 .await?;
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. sms::fake() records messages instead of sending them, and checks each one as a real send would, so an invalid number still fails the test:
1use laravel::model::create;2use laravel::sms;3use laravel::testing::prelude::*;45#[laravel::test]6async fn customers_hear_when_their_order_ships(app: Application) -> laravel::Result<()> {7 let user = create!(User {8 name: "Taylor",10 password: "password",11 phone: "+15555550123",12 })13 .await?;14 let order = create!(Order { user_id: user.id, total: 2500 }).await?;15 let sms = sms::fake();1617 app.post(format!("/orders/{}/ship", order.id)).await.assert_redirect();1819 sms.assert_sent_where(|message| {20 message.to() == "+15555550123" && message.text().contains("has shipped")21 });2223 Ok(())24}1use laravel::model::create;2use laravel::sms;3use laravel::testing::prelude::*;45#[laravel::test]6async fn customers_hear_when_their_order_ships(app: Application) -> laravel::Result<()> {7 let user = create!(User {8 name: "Taylor",10 password: "password",11 phone: "+15555550123",12 })13 .await?;14 let order = create!(Order { user_id: user.id, total: 2500 }).await?;15 let sms = sms::fake();1617 app.post(format!("/orders/{}/ship", order.id)).await.assert_redirect();1819 sms.assert_sent_where(|message| {20 message.to() == "+15555550123" && message.text().contains("has shipped")21 });2223 Ok(())24}
The fake counts send as sent and queue as queued, and has assertions for each:
| Method | Asserts or returns |
|---|---|
assert_sent_where(predicate), assert_queued_where(predicate) |
A sent, or queued, message matches the predicate |
assert_sent_times(count), assert_queued_times(count) |
Exactly count messages were sent, or queued |
assert_nothing_sent() |
No message was sent or queued |
sent(), queued() |
Each sent, or queued, message, in order |
The predicate receives the message, with to(), from(), and text(). A queued message also has connection(), queue(), and delay(), so you may check where its job would go:
1sms.assert_queued_where(|message| message.queue() == "sms" && message.delay() == 5.minutes());1sms.assert_queued_where(|message| message.queue() == "sms" && message.delay() == 5.minutes());