Send SMS From Laravel App Using Vonage
Tags: laravel, php, sms, vonage
Published: 2023-01-12 23:51:11

---
title: Send SMS From Laravel App Using Vonage
published: true
date: 2022-07-09 08:05:24 UTC
tags: 
- Laravel
- PHP
- SMS
- Vonage
canonical_url: https://fajarwz.com/blog/send-sms-from-laravel-app-using-vonage/
---
![Sending SMS illustration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pao6cuyph886lbeoxhqs.png)

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](https://www.vonage.co.uk/) or [Twilio](https://www.twilio.com/).

In this tutorial, we'll be using Vonage to send our SMS with the help of [laravel/vonage-notification-channel package](https://github.com/laravel/vonage-notification-channel).

## Create A Vonage Account
Now you want to [create a Vonage account](https://ui.idp.vonage.com/ui/auth/registration) and verify your email. After that you can go to [Vonage Dashboard](https://dashboard.nexmo.com/).

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](https://dashboard.nexmo.com/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](https://github.com/laravel/vonage-notification-channel), a Laravel's first party package.

```
composer require laravel/vonage-notification-channel
```

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
```

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

![Vonage dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rl1121kesmyoeh9ea00w.jpg)

## 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
```

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

```php
// App\Notifications\SuccessfulRegistration.php

public function via($notifiable)
{
    return ['vonage'];
}
```

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

```php
// 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 . '!');
    }

    // ...
}
```

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:

```php
Schema::create('users', function (Blueprint $table) {
    ...
    $table->string('phone_number');
    ...
});
```

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

```php
public function definition()
{
    return [
        ...
        'phone_number' => fake()->phoneNumber(), 
        ...
    ];
}
```

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

```php
public function run()
{
    \App\Models\User::factory(10)->create();
}
```

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:

```php
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;
    }
}
```

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.

```php
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!';
}

```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n1ma53hh0amp4c4kowx3.jpeg)

### 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
```

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

```php
return [
    // ...
    'admin_sms_number' => env('VONAGE_SMS_FROM'),
    // ...
]
```

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

```php
<?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 [
            //
        ];
    }
}

```

And then call it inside a method in our controller.

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

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

## 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](https://github.com/fajarwz/blog-laravel-sms-vonage).

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

## Further Reading
* [SMS Notifications - Laravel Docs](https://laravel.com/docs/9.x/notifications#sms-notifications)
* [SMS API | Vonage](https://www.vonage.com/communications-apis/sms/)


## Read also:
* [Send Slack Notifications From Laravel App](https://fajarwz.com/blog/send-slack-notifications-from-laravel-app/)