DEV Community

Cover image for How to send SMS Notifications in Laravel using Twilio
Snehal Rajeev Moon
Snehal Rajeev Moon

Posted on • Updated on

How to send SMS Notifications in Laravel using Twilio

Hello Artisans,

In this blog post we will see how we can send sms notifications using laravel.

In Laravel, we can send SMS notifications using a package such as Twilio or Nexmo. In this post we are going to see how we can send SMS using Twilio package.

So let's get started by installing Twilio package:

composer require twilio/sdk
Enter fullscreen mode Exit fullscreen mode

Create a new notification class using the php artisan make:notification command.

php artisan make:notification SendSMS
Enter fullscreen mode Exit fullscreen mode

In the newly created notification class, add a toTwilio method. This method will contain the logic for sending the SMS using the Twilio package.

use Twilio\Rest\Client;

public function toTwilio($notifiable)
{
    $twilio = new Client(env('TWILIO_SID'), env('TWILIO_TOKEN'));

    $message = $twilio->messages
                    ->create("+1234567890", // to
                        array(
                            "body" => "Hello from Laravel!",
                            "from" => "+0987654321"
                        )
                    );
    return $message;
}
Enter fullscreen mode Exit fullscreen mode

In the above code you need to replace TWILIO_SID and TWILIO_TOKEN with your Twilio account SID and token respectively. Also replace the "to" and "from" numbers with the phone numbers you want to send the message to and from.

To send the notification, you can use the Notification facade's send method and pass it the notifiable instance and the notification class.

Notification::send($user, new SendSMS());
Enter fullscreen mode Exit fullscreen mode

Now you can send SMS notification to the user.

Note: You also need to config your Twilio account with phone numbers and other settings.

Thank You!!
Happy Reading 🦄 ❤️

Oldest comments (0)