Sling Academy
Home/PHP/SMS Notifications in Laravel: A Practical Guide

SMS Notifications in Laravel: A Practical Guide

Last updated: January 16, 2024

Overview

With the increasing necessity for real-time communication in web applications, SMS notifications provide a powerful tool to reach users immediately and effectively. In this tutorial, we’ll explore how to send SMS notifications in a Laravel application, leveraging Laravel’s built-in notifications system and various SMS services.

Notification API in Laravel

Laravel provides a clean, simple API for various notification channels, including SMS. The abstraction provided by Laravel allows smooth switching between different sending services such as Nexmo (Vonage), Twilio, and others.

Setting up Your Laravel Project

  1. Start by creating a new Laravel project or navigate to your existing project directory.
  2. Ensure you have the necessary models to which you’ll be sending notifications, typically users.

Configuring the SMS Service

You need to choose an SMS provider and configure it within your Laravel application. In this guide, we will use Nexmo as an example.

  1. Install the Nexmo client by running composer require nexmo/client.
  2. Add your Nexmo credentials to your .env file.

Creating Notifications

Create a new notification with php artisan make:notification SendSMSNotification command.

Utilize the Nexmo Channel

Edit the SendSMSNotification class to use the Nexmo SMS channel.

public function via($notifiable)
{
    return [\'nexmo\'];
}

public function toNexmo($notifiable)
{
    return (new \Nexmo\Message\SMS())
        ->content('Your notification text here.')
        ->from('Your_Nexmo_Number');
}

Sending Notifications

Use the notify method on your notifiable model instance to send a notification.

use App\Notifications\SendSMSNotification;

$user->notify(new SendSMSNotification());

Advanced – Queueing Notifications

To prevent delays in user experience, you should queue your notifications.

public function via($notifiable)
{
    return ['nexmo', 'database', 'broadcast'];
}

Utilize Laravel’s job queue by implementing the ShouldQueue interface within your notification class.

use Illuminate\Contracts\Queue\ShouldQueue;

class SendSMSNotification extends Notification implements ShouldQueue
{
    //...
}

Handling Delivery Response

Modify the toNexmo method to handle the delivery response and perform actions based on this response.

//...

\Nexmo\Message\(new \Nexmo\Message\SMS())
    ->send();

// Handle the response here

//...

Error Handling and Logging

Implement try-catch blocks in your notification sending logic to handle any errors and log them appropriately.

try {
    $response = $message->send();
} catch (\Exception $e) {
    \Log::error($e->getMessage());
}

Customizing the Notifiable Model

Add the routeNotificationForNexmo method in your notifiable model to customize the phone number to which notifications will be sent.

public function routeNotificationForNexmo($notification)
{
    return $this->phone;
}

Conclusion

In conclusion, integrating SMS notifications into your Laravel project is straightforward with the robust capabilities offered by Laravel’s notification system. By harnessing the power of Laravel and the flexibility of various SMS services, you can provide a seamless and responsive experience to your users.

Next Article: How to verify email in Laravel (with examples)

Previous Article: Laravel + Eloquent: Design a Simple URL Shortening Service

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array