Home » Laravel Twilio Send SMS Tutorial With Example

Laravel Twilio Send SMS Tutorial With Example

Last updated on May 23, 2022 by

In this article, we will learn Laravel Twilio sending SMS tutorial with example. We will use the composer package twilio/sdk to send SMS using the Laravel. Let’s just see how to do it.

Step 1: Install Laravel

If you already have installed Laravel on your local machine then you can skip this step. You can easily install the fresh version of Laravel by running the below command in your terminal. You can give it any name but in this case, we will name it demo-app.

composer create-project --prefer-dist laravel/laravel demo-app

Step 2: Install twilio/sdk Package

Next, we need to install twilio/sdk composer package to use Twilio API. Change your current working directory to demo-app and run the composer command as below:

cd demo-app
composer require twilio/sdk

If you don’t have composer installed on your PC you can do so by following the instructions here.

Step 3: Create Twilio Account

First, we need to create a Twilio account. Then, go to your Twilio dashboard and grab your Account SID and Auth Token.

laravel twillio get credentials

Now go to the Phone Number menu section to get your SMS-enabled phone number.

laravel twillio send sms tutorial get phone number

Step 4: Update .env File

The next step is to update the .env file with your Twilio credentials. So open up .env located at the root of the project directory and add the following values:

TWILIO_SID="INSERT YOUR TWILIO SID HERE"
TWILIO_AUTH_TOKEN="INSERT YOUR TWILIO TOKEN HERE"
TWILIO_NUMBER="+91***************"

Step 5: Create SmsController

Let’s create a SmsController and let’s add two methods, one for the display SMS sending form and the second for the sending messages to the receiver. To create a controller run the below command:

php artisan make:controller SmsController

After running the above command a new file will be created in Controllers directory, open it, and add the following method.

app/Http/Controllers/SmsController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Twilio\Rest\Client;

class SmsController extends Controller
{
    public function index()
    {
        return view('send-sms');
    }

    public function sendMessage(Request $request)
    {
        $this->validate($request, [
            'receiver' => 'required|max:15',
            'message' => 'required|min:5|max:155',
        ]);

        try {
            $accountSid = getenv("TWILIO_SID");
            $authToken = getenv("TWILIO_TOKEN");
            $twilioNumber = getenv("TWILIO_FROM");

            $client = new Client($accountSid, $authToken);

            $client->messages->create($request->receiver, [
                'from' => $twilioNumber,
                'body' => $request->message
            ]);

            return back()
            ->with('success','Sms has been successfully sent.');

        } catch (\Exception $e) {
            dd($e->getMessage());
            return back()
            ->with('error', $e->getMessage());
        }
    }
}

Step 6: Create Routes

We need to add two routes in routes/web.php file to perform the Laravel Twilio send SMS. The first GET route is used to show the sending SMS form and another route for the POST method to send the SMS to the receiver in Laravel.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SmsController;


Route::get('send-sms', [ SmsController::class, 'index' ])->name('get.sms.form');
Route::post('send-sms', [ SmsController::class, 'sendMessage' ])->name('send.sms');

Step 7: Create Blade/HTML File

At last, we need to create a send-sms.blade.php file in the views folder and in this file, we will add the video upload Form HTML.

resources\views\send-sms.blade.php

<!DOCTYPE html>
<html>
   <head>
      <title>Laravel Twilio Send SMS Form - ScratchCode.io</title>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
   </head>
   <body>
      <div class="container mt-5">
         <div class="panel panel-primary">
            <div class="panel-heading">
               <h2>Laravel Twilio Send SMS Form - ScratchCode.io</h2>
            </div>
            <div class="panel-body">
               @if ($message = Session::get('success'))
	               <div class="alert alert-success alert-block">
	                  <button type="button" class="close" data-dismiss="alert">×</button>
	                  <strong>{{ $message }}</strong>
	               </div>
               @endif

               @if (count($errors) > 0)
               <div class="alert alert-danger">
                  <strong>Whoops!</strong> There were some problems with your input.
                  <ul>
                     @foreach ($errors->all() as $error)
                     <li>{{ $error }}</li>
                     @endforeach
                  </ul>
               </div>
               @endif

               <form action="{{ route('send.sms') }}" method="POST" enctype="multipart/form-data">
                  @csrf
                  <div class="row">

                     <div class="col-md-12">
                        <div class="col-md-6 form-group">
                           <label>Receiver Number:</label>
                           <input type="text" name="receiver" class="form-control"/>
                        </div>
                        <div class="col-md-6 form-group">
                           <label>Message:</label>
                           <textarea name="message" class="form-control"></textarea>
                        </div>
                        <div class="col-md-6 form-group">
                           <button type="submit" class="btn btn-success">Send SMS</button>
                        </div>
                     </div>
                  </div>
               </form>
            </div>
         </div>
      </div>
   </body>
</html>

If you have SSL error then follow the following step:

1. Download the following file – cacert.pem
2. Then download the following file – thawte_Premium_Server_CA.pem
3. Open the second file in a text editor and copy its contents into the first file (cacert.pem at the bottom/end).
Save cacert.pem and add the following lines to your php.ini :

[curl]
curl.cainfo=c:/xampp/php/cacert.pem

Obviously, change the directory to the one where your pem is located. Restart the PHP local server (xampp/wamp). Then it will work flawlessly.

Step 8: Output

Hurray! We have completed all steps for the Laravel Twilio send SMS. Let’s run the below command and see how it’s working.

php artisan serve

After running the above command, open your browser and visit the site below URL:

http://localhost:8000/send-sms

Additionally, read our guide:

  1. Laravel: Blade Switch Case Statement Example
  2. Laravel: Switch Case Statement In Controller Example
  3. Laravel: Change Column Type In Migration
  4. Laravel: Change Column Name In Migration
  5. How To Use Where Date Between In Laravel
  6. How To Add Laravel Next Prev Pagination
  7. Laravel Remove Column From Table In Migration
  8. Laravel: Get Month Name From Date
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Update Pivot Table In Laravel
  11. How To Install Vue In Laravel 8 Step By Step
  12. How To Handle Failed Jobs In Laravel
  13. Best Ways To Define Global Variable In Laravel
  14. How To Get Latest Records In Laravel
  15. How To Break Nested Loops In PHP Or Laravel
  16. How To Pass Laravel URL Parameter
  17. Laravel Run Specific Migration
  18. Redirect By JavaScript With Example
  19. How To Schedule Tasks In Laravel With Example
  20. Laravel Collection Push() And Put() With Example

That’s it from our end. We hope this article helped you to learn the Laravel Twilio send SMS tutorial with the example.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post 🙂 Keep Smiling! Happy Coding!

 
 

Leave a Comment