Laravel 8 SMS Notification with Vonage API Example
Tags: laravel, programming, tutorial, beginners
Published: 2022-04-22 07:22:10

Originally posted @ https://codeanddeploy.com visit and download the sample code:
https://codeanddeploy.com/blog/laravel/laravel-8-sms-notification-with-vonage-api-example

In this post, I will show you how to implement **Laravel 8 SMS notification** using Vonage API (formerly known as Nexmo). Sometimes we need to implement a notification that will directly send an SMS to your user transaction.

 

In my previous post, I shared about Laravel Email Notification and now let's dig about SMS notification that we can implement along with Email notification.

 

Laravel is smoothly working with Vonage API so we will use it as our SMS provider. So if you don't have an account just register here.

 

Now let's start.

 

## Step 1: Laravel Installation

If you don't have a Laravel 8 install in your local just run the following command below:


```php
composer create-project --prefer-dist laravel/laravel laravel-sms-notification
```

## Step 2: Database Configuration
If your **Laravel project** is fresh then you need to update your database credentials. Just open the .env file in your Laravel 8 project.

 
`.env`

```php

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name_here
DB_USERNAME=your_database_username_here
DB_PASSWORD=your_database_password_here
```

## Step 3: Migration Setup
Here we need to generate first the **notifications** table before running the migrations. Kindly run the following command:

```php
php artisan notifications:table
```

Because we are using phone_number from user table we need to add this field from your user migration. See below example code.

```php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name')->nullable();
            $table->string('email')->unique();
            $table->string('phone_number')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->softDeletes();
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}
```

If you user already exists then you must add your phone_number column using migration.


Then once done. Kindly run the following command:

```php
php artisan migrate
```

Then once done let's create a seeder for our user. Run the following command:

```php
php artisan make:seeder CreateUsersSeeder
```
Once our seeder is generated kindly to the **database/seeders** directory. Open the CreateUsersSeeder.php and you will see the following code:

```php
<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Seeder;

class CreateUsersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        User::create([
            'name' => 'Juan',
            'email' => 'email@gmail.com',
            'phone_number' => '63926*******',
            'password' => bcrypt('password')
        ]);
    }
}
```

Then run the following command:


```php
php artisan db:seed --class=CreateUsersSeeder
```
[Learn more about Laravel seeder here.
](https://codeanddeploy.com/blog/laravel/creating-a-seeder-in-laravel-8)

## Step 4: Install Package & Connect Vonage API
To work with SMS notification using Vonage we need to install vonage channel notification via composer:

```php
composer require laravel/nexmo-notification-channel
```
Once installed let's connect Vonage API to our Laravel App. Login to your Vonage account and click "Getting started".

![laravel-8-sms](https://ecn-storage.s3.us-west-2.amazonaws.com/articles/laravel-8-sms-notification-with-vonage-api-example-V6GxJSDAAwx980.webp?ctm=1637146781)

Then add the credentials to your .ENV file.

```php
NEXMO_KEY=key_here
NEXMO_SECRET=secret_here
```
Next we will add `sms_from` to our c`onfig/services.php` file. The `sms_from` is the phone number to use for sending message and will be sent from.

```php
'nexmo' => [
    'sms_from' => 'Vonage SMS API HERE',
],
```

Note: You can also use a custom phone number or Sender ID via Vonage dashboard and then set the value here.

## Step 5: Create Laravel SMS Notification

Now, let's generate our Laravel sms notification class example we will name this as SMSNotification. Run the following command to do this.


```php
php artisan make:notification SMSNotification
```

Once done, navigate `App/Notifications` and open `EmailNotification.php` then edit it. See below example:

```php
<?php

namespace App\Notifications;

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

class SMSNotification extends Notification
{
    use Queueable;

    /**
     * @var array $project
     */
    protected $project;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($project)
    {
        $this->project = $project;
    }

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

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->greeting($this->project['greeting'])
                    ->line($this->project['body'])
                    ->action($this->project['actionText'], $this->project['actionURL'])
                    ->line($this->project['thanks']);
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toDatabase($notifiable)
    {
        return [
            'project_id' => $this->project['id']
        ];
    }

    /**
     * Get the Nexmo / SMS representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return NexmoMessage
     */
    public function toNexmo($notifiable)
    {
        return (new NexmoMessage)
                    ->content($this->project['greeting'] . ' ' . $this->project['body']);
    }

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

## Step 6: Setting up Routes
Next we will create a route for our SMS notification sending. Just open the **"routes/web.php"** file and add the following routes.

```php
<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('/send', '\App\Http\Controllers\HomeController@send')->name('home.send');
 
```

## Step 7: Setting Up Controller
In this section we will add our SMS notification in our HomeController as we set in our routes. See below complete code of our controller:

```php
<?php

namespace App\Http\Controllers;

use Notification;
use App\Models\User;
use Illuminate\Http\Request;
use App\Notifications\SMSNotification;

class HomeController extends Controller
{
    public function send() 
    {
    	$user = User::first();
  
        $project = [
            'greeting' => 'Hi '.$user->name.',',
            'body' => 'This is the project assigned to you.',
            'thanks' => 'Thank you this is from codeanddeploy.com',
            'actionText' => 'View Project',
            'actionURL' => url('/'),
            'id' => 57
        ];
  
        Notification::send($user, new SMSNotification($project));
   
        dd('Notification sent!');
    }
}
```

Next, we need to add a method for our SMS notification in our model so that the Vonage package will know what column we are using for sending SMS. Add this in your User.php model.

```php
public function routeNotificationForNexmo($notification)
{
    return $this->phone_number;
}
```

Here is the complete model code.


```php
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'phone_number',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

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

Now are good to go and test our SMS notification using Laravel.

 

You can test it now by running the serve command:

```php
php artisan serve
```

Then run the url below to your browser to send SMS notification to your user.

```php
http://127.0.0.1:8000/send
```

Now you will see this output in your phone.


![laravel-8-sms-notification](https://ecn-storage.s3.us-west-2.amazonaws.com/articles/laravel-8-sms-notification-with-vonage-api-example-qUT4PR1vV3x980.webp?ctm=1637147875)

Issue for Trial account.

![laravel-8-sms](https://ecn-storage.s3.us-west-2.amazonaws.com/articles/laravel-8-sms-notification-with-vonage-api-example-SYnkISzKqVx980.webp?ctm=1637148177)

Solution: To prevent the above error you need to register your mobile number you will sending for test. Visit [here](https://help.nexmo.com/hc/en-us/articles/204014853-How-do-I-add-test-numbers-during-my-Vonage-API-trial-) for more details.

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/laravel-8-sms-notification-with-vonage-api-example if you want to download this code.

Happy coding :)