How to send SMS using Laravel 5 notification

In the post, we will be focusing on sending SMS Laravel notification. We will use Nexmo API for sending SMS notification. Since this is a continuation from the previous article about sending email notification in Laravel, I will not go through the basic setup.

Getting Nexmo Credentials

For this post, we will use a Nexmo API. For this, you need to signup for Nexmo. Fill up the forms with required details, after you complete your registration, you will be redirected to dashboard where you will get your API credentials.

Install Nexmo Client package.

We will use composer to install it.

Nexmo Configuration

After installing nexmo client, we need to add configuration in services.php with nexmo credentials.

Now add these credentials in our .env file.

Add phone number to users table

We need a field for storing the phone number of the user. So, we will add a column to the users table. Our Users table migration looks like below:

Create Notification

Run the following artisan command to create AccountCreatedSMS notification:

It will create new file App/Notification/AccountCreatedSMS. In this file has two methods i.e. via method and toMail method.

The via method is used to determine which channels the notification will be delivered like emails, SMS, and Slack. We will change the default via method. So, our via method looks like below:

Similarly, we will add new method toNexmo to send SMS notification.

Thus, our complete notification file looks like below:

Configure User Model

To use notification, need to use Notifiable trait in User model.

Add Phone number input field to register blade file

We need to add a separate field for a mobile number of the user. Simply add a new field below your email address field as below:

Sending Notification

After all our setup, we need to fire our notification. We will send SMS notification after the user is registered. Thus, we changed our controller file accordingly. Our final controller file looks like below:

This is all for SMS notification in Laravel. After a new user is created, it will send a new SMS to the respective phone number. ou can official documentation from Nexmo here.

Leave a Reply

Your email address will not be published. Required fields are marked *