Jyrone Parker

Sending Twilio Notifications With Laravel 5.3

[callaction url=”https://www.youtube.com/user/JPlaya01″ background_color=”#333333″ text_color=”#ffffff” button_text=”Go Now” button_background_color=”#e64429″]Subscribe To My Youtube Page[/callaction]

Sending Twilio Notifications With Laravel 5.3

One of the greatest features added to Laravel 5.3 IMHO was the introduction of notifications. Notifications allow you to send messages to users over a variety of channels including mail, sms, and slack. You also have the option of storing them in the database. “THIS IS GREAT” I thought as I was reading up on it and contemplating how I was going to refactor my existing hoemebrew Twilio notification systems. There was just one problem. The Laravel notification system’s default SMS driver is for Nexmo, not Twilio! Luckily I found a solution, and I am going to share it with you today

The Application

The application I am going to walk you through writing a simple Laravel 5.3 app that signs users up and sends them daily inspirational quotes. The order of which the application will be written is thus:

  • Create App/Install dependencies
  • Prepare database/Registration
  • Create notification
  • Modify inspire console command

While this application won’t be very exciting, it will demonstrate the groundwork needed to get Twilio up and running in your web application.

Creating App/Installing Dependencies

First off we must create the application open up your terminal and use the following command

laravel new TwilioNotifications

Once the appcation has been scaffolded cd into the new directory and add the following composer package

composer require laravel-notification-channels/twilio

This will add the Twilio dependency we need to make SMS notifications. Now we need to add the following to the providers array in config/app.php

// config/app.php
'providers' => [
    ...
    NotificationChannels\Twilio\TwilioProvider::class,
],

Next we need to update our config/services.php file and add the Twilio credentials

 

// config/services.php
...
'twilio' => [
    'account_sid' => env('TWILIO_ACCOUNT_SID'),
    'auth_token' => env('TWILIO_AUTH_TOKEN'),
    'from' => env('TWILIO_FROM'), // optional
],
...

Make sure you update you .env file to suit, other than that we are ready to go onto the database/registration logic.

Database/Registration

Open up the default database migration. We just need to add a ‘phone_number’ attribute to the migration, add the following

$table->string('phone_number');

You can safely run your migration, nothing else to be done here. Now we need to scaffold the application of authentication logic, please enter the following command in your terminal.

php artisan make:auth

This command creates the views, controllers, and routes for registering users, we just need to add some logic to accommodate for phone_number. First open up resources/views/auth/register.blade.php and underneath the email block of HTML add the following:


<div class="form-group{{ $errors->has('phone_number') ? ' has-error' : '' }}">
<label for="phone" class="col-md-4 control-label">Phone</label>

<div class="col-md-6">
<input id="phone_number" type="tel" class="form-control" name="phone_number" value="{{ old('phone_number') }}" required>

@if ($errors->has('phone_number'))
<span class="help-block">
<strong>{{ $errors->first('phone_number') }}</strong>
</span>
@endif
</div>
</div>

Next open up app/Http/Controllers/Auth/RegisterController.php in your Validator array add the following rule:

'phone_number' => 'required'

In the create method simply add the following in the User::Create array:

'phone_number' => $data['phone_number'],

You should be able to register accounts now! On to the next part, creating the notification

Creating The Notification

Laravel provides an artisan command for creating notifications. Go to the terminal and enter the following

php artisan make:notification InspireUser

This will create a Notifications folder under app/, go there and open InspireUser.php file

In the constructor we are going to be passing in a quote string so we should grab and set it


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

Look at the via($notifiable) method, notice is returns an array of channels to send the message to. Since we are not using mail in this example you can safely remove that and replace it with this


public function via($notifiable)
{
return [TwilioChannel::class];
}

Be sure to add the following use clauses at the top


use NotificationChannels\Twilio\TwilioChannel;
use NotificationChannels\Twilio\TwilioSmsMessage;

For every channel you want to broadcast on you must have a corresponding method toChannel($notifiable). So for Twilio we need a toTwilio($notifiable) where $notifiable is the class that is being notified.


public function toTwilio($notifiable)
{
return (new TwilioSmsMessage())
->content("Hello {$notifiable->name} here is your inspiring quote for the day: {$this->quote}");
}

That’s all we have to do, now on to the last part, modifying the inspire console command.

Modifying The Inspire Console Command

Laravel ships with a predefined console command called inspire, it simply echos an inspiring quote to the console. It’s located in routes/console.php delete everything and replace it with this


<?php

use Illuminate\Foundation\Inspiring;
use App\User;
use App\Notifications\InspireUser;
/*
|--------------------------------------------------------------------------
| Console Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of your Closure based console
| commands. Each Closure is bound to a command instance allowing a
| simple approach to interacting with each command's IO methods.
|
*/

Artisan::command('inspire', function () {
$users = User::all();
$users->each(function($item, $key){
$this->info("Notifying {$item->name}");
$item->notify(new InspireUser(Inspiring::quote()));
});
})->describe('Send an in inspiring quote to all your users');

This version of inspire grabs all the users and sends them a text message with the inspiring quote. You can go to the terminal and type

 php artisan inspire

and all your users will be notified. That’s it in a nutshell, although I would advise putting this command on a daily schedule so you don’t have to manually go into the terminal everyday, but I will leave you to that. If you would like to see the source code, it is available here on Github.

Leave a Reply

Instagram

Follow Me!

%d bloggers like this: