DEV Community

Cover image for Laravel 8 SMS Notification with Vonage API Example
Code And Deploy
Code And Deploy

Posted on

Laravel 8 SMS Notification with Vonage API Example

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:

composer create-project --prefer-dist laravel/laravel laravel-sms-notification
Enter fullscreen mode Exit fullscreen mode

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


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
Enter fullscreen mode Exit fullscreen mode

Step 3: Migration Setup

Here we need to generate first the notifications table before running the migrations. Kindly run the following command:

php artisan notifications:table
Enter fullscreen mode Exit fullscreen mode

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

<?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');
    }
}
Enter fullscreen mode Exit fullscreen mode

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

Then once done. Kindly run the following command:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

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

php artisan make:seeder CreateUsersSeeder
Enter fullscreen mode Exit fullscreen mode

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

<?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')
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Then run the following command:

php artisan db:seed --class=CreateUsersSeeder
Enter fullscreen mode Exit fullscreen mode

Learn more about Laravel seeder here.

Step 4: Install Package & Connect Vonage API

To work with SMS notification using Vonage we need to install vonage channel notification via composer:

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

Once installed let's connect Vonage API to our Laravel App. Login to your Vonage account and click "Getting started".

laravel-8-sms

Then add the credentials to your .ENV file.

NEXMO_KEY=key_here
NEXMO_SECRET=secret_here
Enter fullscreen mode Exit fullscreen mode

Next we will add sms_from to our config/services.php file. The sms_from is the phone number to use for sending message and will be sent from.

'nexmo' => [
    'sms_from' => 'Vonage SMS API HERE',
],
Enter fullscreen mode Exit fullscreen mode

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 artisan make:notification SMSNotification
Enter fullscreen mode Exit fullscreen mode

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

<?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 [
            //
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

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

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');

Enter fullscreen mode Exit fullscreen mode

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

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!');
    }
}
Enter fullscreen mode Exit fullscreen mode

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.

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

Here is the complete model code.

<?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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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

You can test it now by running the serve command:

php artisan serve
Enter fullscreen mode Exit fullscreen mode

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

http://127.0.0.1:8000/send
Enter fullscreen mode Exit fullscreen mode

Now you will see this output in your phone.

laravel-8-sms-notification

Issue for Trial account.

laravel-8-sms

Solution: To prevent the above error you need to register your mobile number you will sending for test. Visit here 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 :)

Top comments (0)