DEV Community

Fajar Windhu Zulfikar
Fajar Windhu Zulfikar

Posted on • Originally published at fajarwz.com on

Send SMS From Laravel App Using Vonage

Sending SMS illustration

Maybe right now you need to send an SMS via Laravel app. There are some Laravel packages that can connect to third-party service that can handle SMS notification such as Vonage or Twilio.

In this tutorial, we'll be using Vonage to send our SMS with the help of laravel/vonage-notification-channel package.

Create A Vonage Account

Now you want to create a Vonage account and verify your email. After that you can go to Vonage Dashboard.

When we first sign up, our account has €2 EUR free credit and we can use it on up to 10 numbers for demo mode until we top up our account. These 10 numbers should be registered first to our test numbers, but this whitelisting only apply in the free demo mode, paid clients don't have this limitation. Demo mode messages also contain a watermark at the end of it's message (which says "[FREE SMS DEMO, TEST MESSAGE]").

Every message I send Vonage charge me for €0.18. This is a good start to experiment with Vonage and check whether it is a good fit for your project or not. Once you sure to add Vonage to your project, you can top up your account.

Installation

After we create a Vonage account, we can continue to install the laravel/vonage-notification-channel, a Laravel's first party package.

composer require laravel/vonage-notification-channel
Enter fullscreen mode Exit fullscreen mode

After the installation completed, we can head to .env file and add the following key with your own value.

VONAGE_KEY=your-vonage-key
VONAGE_SECRET=your-vonage-secret
Enter fullscreen mode Exit fullscreen mode

VONAGE_KEY and VONAGE_SECRET can be obtained from your Vonage dashboard account.

Vonage dashboard

Generate Notifications

Create a class for our spesific notification with below artisan command, for example we create a SuccessfulRegistration notification. This will generate the class in App\Notifications folder. If we don't have the folder yet, Laravel will create one for us.

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

Make sure to change the via method to return vonage in the SuccessfulRegistration class

// App\Notifications\SuccessfulRegistration.php

public function via($notifiable)
{
    return ['vonage'];
}
Enter fullscreen mode Exit fullscreen mode

Create Notification format

Use the toVonage method and format the notification. We can create a simple message like so:

// App\Notifications\SuccessfulRegistration.php

use Illuminate\Notifications\Messages\VonageMessage;
use Illuminate\Contracts\Queue\ShouldQueue;

class SuccessfulRegistration extends Notification implements ShouldQueue
{
    use Queueable;

    // Here we will also pass the name variable
    public function __construct(private string $name)
    {
        //
    }

    // ...

    /**
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\SlackMessage
     */
    public function toVonage($notifiable)
    {
        return (new VonageMessage())
            ->content('Welcome to My App, ' . $this->name . '!');
    }

    // ...
}
Enter fullscreen mode Exit fullscreen mode

Notice that I've also implements the ShouldQueue interface. This means that when we use SMS service in our request, we can immediately send our response return to the user without the need to wait for the SMS to be sent first. The SMS task will be send to our project's queue workers in the background.

Sending Notifications

We can send the notification in two ways: Using Trait and Facade

Using Trait

For example, we want to send a SMS to our users and we have their phone number stored in phone_number field. If you try to follow this tutorial with a new installation of Laravel, you want to add a phone_number field to your users table migration file first like so:

Schema::create('users', function (Blueprint $table) {
    ...
    $table->string('phone_number');
    ...
});
Enter fullscreen mode Exit fullscreen mode

Then add this to your database/factories/UserFactory.php

public function definition()
{
    return [
        ...
        'phone_number' => fake()->phoneNumber(), 
        ...
    ];
}
Enter fullscreen mode Exit fullscreen mode

And add this to your database/seeders/DatabaseSeeder.php

public function run()
{
    \App\Models\User::factory(10)->create();
}
Enter fullscreen mode Exit fullscreen mode

Then execute php artisan migrate --seed.

After we have user's phone number in our users table then create a new routeNotificationForVonage method on our User model that return phone_number field. And make sure that our User model use Notifiable trait like so:

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    // ...

    public function routeNotificationForVonage($notification)
    {
        return $this->phone_number;
    }
}
Enter fullscreen mode Exit fullscreen mode

Now whenever we try to send a SMS to a user using Trait method, we will use their phone number stored in phone_number field.

Finally, to send a SMS to the user we can use the notify() method that is provided by this trait to send the notification.

use App\Models\User;
use App\Notifications\SuccessfulRegistration;


public function byUserModel() {
    $user = User::findOrFail(1);

    $user->notify(new SuccessfulRegistration($user->name));

    return 'Send SMS via Vonage success!';
}

Enter fullscreen mode Exit fullscreen mode

After the above action executed, our user whose name "John Thor" should see a SMS message saying "Welcome to My App, John Thor!".

Here is another examples of the SMS sent using Vonage.

SMS example

Using The Notification Facade

Another way is using Notification facade. We can use this in any class.

For example the use case here is to notify our admin whenever there is an invoice that has been paid.

I use .env and config/app.php to store the admin number so I made this configuration. First I add another .env variable like so:

VONAGE_SMS_FROM=62xxxxxxxx
Enter fullscreen mode Exit fullscreen mode

And add below key and value to the config/app.php.

return [
    // ...
    'admin_sms_number' => env('VONAGE_SMS_FROM'),
    // ...
]
Enter fullscreen mode Exit fullscreen mode

I also make another notification so it can fit our use case.

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\VonageMessage;
use Illuminate\Notifications\Notification;

class InvoicePaid extends Notification implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(private string $invoiceNumber)
    {
        //
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['vonage'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toVonage($notifiable)
    {
        return (new VonageMessage)
            ->from('My App')
            ->content('Invoice number ' .$this->invoiceNumber . ' has been paid!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

Enter fullscreen mode Exit fullscreen mode

And then call it inside a method in our controller.

use Illuminate\Support\Facades\Notification;
use App\Notifications\InvoicePaid;

Notification::route('vonage', config('app.admin_sms_number'))
    ->notify(new InvoicePaid('INV-84052'));
Enter fullscreen mode Exit fullscreen mode

Conclusions

That's it, it's easy to send SMS message from Laravel app. First create a Vonage account, install the package required, and send the notification via one of the two ways: Trait or Facade.

A repo for this example case can be found here fajarwz/blog-laravel-sms-vonage.

Any questions about this tutorial? Please comment below 👇, thank you for following this article!

Further Reading

Read also:

Top comments (0)