Laravel and PHP Development Services | Ahex Technologies https://ahex.co/category/laravel-and-php/ Ahex Technologies focuses on offshore outsourcing, by providing innovative and quality services and value creation for our clients. Wed, 18 Oct 2023 08:14:07 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.3 202019870 Test Driven Development Using Laravel https://ahex.co/test-driven-development-using-laravel/?utm_source=rss&utm_medium=rss&utm_campaign=test-driven-development-using-laravel Tue, 26 Jun 2018 11:12:56 +0000 http://ahex.wpenginepowered.com/?p=2233 What is Test Driven Development (TDD) ? Test Driven Development or TDD is a type of software development process where testing starts before writing any code. As the name suggests, in this process it is the “tests” that drives the “development” process. This approach helps a developer to create a detailed layout of what is...

The post Test Driven Development Using Laravel appeared first on Welcome to Ahex Technologies.

]]>
What is Test Driven Development (TDD) ?

Test Driven Development or TDD is a type of software development process where testing starts before writing any code. As the name suggests, in this process it is the “tests” that drives the “development” process. This approach helps a developer to create a detailed layout of what is expected from the code before they even start writing a single line of code. This helps in reducing bugs in short term and, due to automated nature of it, reduces lot of time in regression testing in long term.

TDD in Laravel

Laravel by default provides support for testing using PHPUnit. We are using Laravel 5.6 for this tutorial. Please refer to official docs to get a good understanding of the testing features provided by Laravel. Lets start with writing our first test.

Lets Start the TDD

I am assuming that you have already installed the Laravel. If not please visit official site here to install the Laravel. Once you are done with installation, create a new project using the command:

laravel new learn_tdd

This command will create a new Laravel project learn_tdd. Your project structure will be same as below.

In the project root directory, open the file phpunit.xml, which contains the phpunit configuration for your project. Your phpunit.xml file will be looking like this:


<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>

        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="BCRYPT_ROUNDS" value="4"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
        <env name="MAIL_DRIVER" value="array"/>
    </php>
</phpunit>

During the testing we may have to connect to database or may perform some operations in which database is required. We use sqlite with in memory option, as it is faster and DB is created during the testing process and destroyed in the end. I am adding those options to my phpunit.xml file.


<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>

        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="DB_CONNECTION" value="sqlite"/>
        <env name="DB_DATABASE" value=":memory:"/>
        <env name="BCRYPT_ROUNDS" value="4"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
        <env name="MAIL_DRIVER" value="array"/>
    </php>
</phpunit>

Lets run our first round of test to check that after making changes in the phpunit.xml file, the default tests are running.

So, everything is working fine. Now lets do some test driven development. We are going to create a user registration system using this approach. Let’s begin.

Firstly let us think about the flow of the user registration in perspective with the backend of the system. Breaking that into steps:

Basic steps:

  1. User submits request for registration with the information that is required for registration.
  2. Validate the user submitted data.
  3. Store the information into the database.
  4. Return success status.

Alternative steps:

  1. System validation failed.
  2. System returns the error status with appropriate validation message.

To create our first test class lets use this command:

php artisan make:test UserRegistrationTest

This will create a new file named UserRegistrationTest in the test/Feature folder, containing a default method testExample(), which is auto-generated by artisan while creating the test class for us. The generated file will look like this:

namespace TestsFeature;

use TestsTestCase;
use IlluminateFoundationTestingWithFaker;
use IlluminateFoundationTestingRefreshDatabase;

class UserRegistrationTest extends TestCase
{
    use RefreshDatabase;
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testExample()
    {
        $this->assertTrue(true);
    }
}

Lets write our test by keeping in mind how our users are going to interact with the system. A user fills the the registration form with the required information and then submits it and waits for system to confirm his registration. Mapping these steps to our test class:

<?php

namespace TestsFeature;

use TestsTestCase;
use IlluminateFoundationTestingWithFaker;
use IlluminateFoundationTestingRefreshDatabase;
use IlluminateHttpResponse;

class UserRegistrationTest extends TestCase
{
    use RefreshDatabase;
    /**
     * 
     * @test
     */
    public function a_user_can_register()
    {
        //user fills the form
        $user = [
                'email' => 'test@mail.com',
                'name' => 'Test Name',
                'password' => '12345678',
        ];

        //user submits the form

        $this->json('post', 'api/register', $user)
            ->assertStatus(Response::HTTP_CREATED);
    }
}

In the a_user_can_register( ) method, we are first creating an array to simulate the step of user filling the form. The json( ) method simulates the user submission of the form with the data. We are using POST method as per REST architecture convention, since the data is going to written in the application database (To know more details on this read about REST calls How to build RESTful API using Lavavel 5.6 with Mysql). Once request has been submitted, system assert that we are going to receive a status of 201 from the system.

Please keep in mind, that for phpunit to execute a method as test, we either need to prefix the method name with test or we can add @test in the comment. I am using the later convention, you can use whatever you want or fits your coding policy.

Lets run this test and see what is the result:


 learn_tdd$ vendor/bin/phpunit

PHPUnit 7.1.5 by Sebastian Bergmann and contributors.

 ==> TestsFeatureExampleTest                    ✓  
 ==> TestsFeatureUserRegistrationTest           ✖  
 ==> TestsUnitExampleTest                       ✓  

Time: 191 ms, Memory: 14.00MB

There was 1 failure:

1) TestsFeatureUserRegistrationTest::a_user_can_register
Expected status code 201 but received 404.
Failed asserting that false is true.

/learn_tdd/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:109
/learn_tdd/tests/Feature/UserRegistrationTest.php:29

Oh! our first test failed, but this is what we were expecting. If we closely examine our failure message, it says that we got status message as 404 instead of the 201, which is no surprise, as we have not defined the route. Remember, we are following TDD here, where, test will drive the development and not the other way around. So lets define the route in the routes/api.php file.

Route::post('register', 'RegistrationController@store');

Now lets us run the test again and see whether our test pass or not:

learn_tdd$ vendor/bin/phpunit

PHPUnit 7.1.5 by Sebastian Bergmann and contributors.

 ==> TestsFeatureExampleTest                    ✓  
 ==> TestsFeatureUserRegistrationTest           ✖  
 ==> TestsUnitExampleTest                       ✓  

Time: 374 ms, Memory: 14.00MB

There was 1 failure:

1) TestsFeatureUserRegistrationTest::a_user_can_register
Expected status code 201 but received 500.
Failed asserting that false is true.

/learn_tdd/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:109
/learn_tdd/tests/Feature/UserRegistrationTest.php:29

FAILURES!
Tests: 3, Assertions: 3, Failures: 1.

Surprise! Our test failed again. Let us check the message we got this time. Now we are getting status code of 500 instead of 200, which means there is some internal server error. If we will go back to our routes/api.php file, we can see that we are routing the register request to RegistrationController, but there is no such controller. Let’s create the controller using the this command:

learn_tdd$ php artisan make:controller RegistrationController --resource

This will create RegistrationController in the appHttpControllers directory, auto generated with the methods to handle the REST based request. Lets run the test again,

learn_tdd$ vendor/bin/phpunit                                           

PHPUnit 7.1.5 by Sebastian Bergmann and contributors.


 ==> TestsFeatureExampleTest                    ✓  
 ==> TestsFeatureUserRegistrationTest           ✖  
 ==> TestsUnitExampleTest                       ✓  

Time: 276 ms, Memory: 14.00MB

There was 1 failure:

1) TestsFeatureUserRegistrationTest::a_user_can_register
Expected status code 201 but received 200.
Failed asserting that false is true.

/learn_tdd/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:109
/learn_tdd/tests/Feature/UserRegistrationTest.php:29

FAILURES!
Tests: 3, Assertions: 3, Failures: 1.

It failed again. It was expecting status code 201 but instead it is receiving 200 due to which the test failed. Ok, now let us save the user information into the database and return the appropriate response from our RegistrationController class.

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppUser;
use IlluminateSupportFacadesHash;
use IlluminateHttpResponse;

class RegistrationController extends Controller
{
    //..... this part of the code is removed for display purpose

    /**
     * Store a newly created resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    public function store(Request $request)
    {
        
        $user = new User();
        
        //initializing the value
        $user->email = $request->email;
        $user->name = $request->name;
        $user->password = Hash::make($request->password);
        
        //saving the value
        $user->save();
        
        return response([], Response::HTTP_CREATED);
    }

    //..... this part of the code is removed for display purpose
}

Here in the method store( ), we are saving the user submitted data in the database and then returning the 201 response, as per standard HTTP response code for creating a new resource. Now lets run the test again:

➜  learn_tdd$ vendor/bin/phpunit

PHPUnit 7.1.5 by Sebastian Bergmann and contributors.


 ==> TestsFeatureExampleTest                    ✓  
 ==> TestsFeatureUserRegistrationTest           ✓  
 ==> TestsUnitExampleTest                       ✓  

Time: 255 ms, Memory: 18.00MB

OK (3 tests, 3 assertions)

Great! Our test has passed and along with our feature of registering the user details. So, if you followed the steps, we have created one feature using the TDD methodology.  Happy Coding.

Note: We have not covered other features such as factories, validation and there is also some scope of improving the code structure. We will cover those in next few blogs one by one by improving upon what we have done here.

The post Test Driven Development Using Laravel appeared first on Welcome to Ahex Technologies.

]]>
2233
SEND SMS USING TWILIO AND LARAVEL https://ahex.co/send-sms-using-twilio-and-laravel/?utm_source=rss&utm_medium=rss&utm_campaign=send-sms-using-twilio-and-laravel Wed, 21 Feb 2018 14:17:54 +0000 http://ahex.wpenginepowered.com/?p=2041 SMS messaging is one of the  most popular way of notifying user about otp, promotional offers and many other updates. In one of my project, there was requirement of sending otp to user’s phone device  and I had to develop web service for web and mobile apps to consume it for sending sms and that...

The post SEND SMS USING TWILIO AND LARAVEL appeared first on Welcome to Ahex Technologies.

]]>
SMS messaging is one of the  most popular way of notifying user about otp, promotional offers and many other updates. In one of my project, there was requirement of sending otp to user’s phone device  and I had to develop web service for web and mobile apps to consume it for sending sms and that is when I stumbled upon Twilio and how by using it with Laravel will give you the result with maximum efficiency and minimum amount of hard work.

In just a matter of few minutes and few lines of code you will be ready to send your first text message. To send a message, just make an HTTP POST to Twilio with the body of the message and the phone number you want to send it to.

Here we will cover the installation and integration of twilio in our project and then use it’s API to send SMS or OTP to a user. Follow the below given steps and then you are good to go. But,before going into the coding part, first let us learn about what twilio is and how does it work?

WHAT IS TWILIO

It is a cloud communication platform as a service. It allows software developer to programmatically make and receive phone calls and send and receive text messages using its web service APIs.This enables businesses to provide the right communications experience for their customers.

Behind Twilio API is a Super Network, a software layer that connects and optimizes communications networks around the world. This is what allows your users to reliably call and message anyone anywhere.Twilio uses Amazon Web Services to host telephony infrastructure and provide connectivity between HTTP and the public switched telephone network (PSTN) through its APIs.

With Twilio, you can reach customers in the ways they prefer, and engage with them effectively using context related to that interaction. As customer experience can increasingly make or break your brand, programmable communications has become more crucial than ever to the success of businesses today.

Sending an SMS or MMS is one of the most common tasks performed on the Twilio Platform. It requires AccountSID and AuthToken, they can be generated by registrting at Twilio.

Getting a Twilio SMS Account:
Here is a link to create an account on twilio if you don’t have one already.

After registration click on Account, there you will be able to see authsid and authtoken. You have assigned a sender mobile number which can be found at Twilio, which is used to send Text Messages or MMS and ShortCodes etc.

Sample Snapshot:

Capture

HOW DOES TWILIO WORK

When you send an SMS/MMS from your web app using Twilio it works like this:

sms-1-way

As you can see sending an SMS is pretty straight forward, and all of this interaction is triggered with just those few lines of code which we will see later.

INSTALLATION:

  • Download package form https://github.com/lakshmaji/twilio
  • OR to install with composer run the following command in your terminal
       composer require lakshmaji/twilio
       Composer dump-autoload
       Composer update

LARAVEL INTEGRATION:

First, you need to add the service provider. Open app/config/app.php, and add a new item to the providers array.

Lakshmaji\Twilio\TwilioServiceProvider::class,

Then, add a Facade for more convenient usage. In app/config/app.php add the following line to the aliases array:

'Twilio' => Lakshmaji\Twilio\Facade\Twilio::class,

Again do composer update again

After completing the above two steps, now open you terminal and create a controller called TwilioTestController. In this controller class we write an example code to send an otp to a user mobile.

Run the below command to create the controller class:

php artisan make:controller  TwilioTestController

Now, go to your TwilioTestController class and write down the below code.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Twilio; 

class TwilioTest extends Controller
{
  public function testMesssage()
  {

    // initialize message array 
    $message_array = array(
        'sender_id'     => 'TWILIO_USER_ID',
        'sender_secret' => 'TWILIO_USER_PASSWORD',
        'receiver_mobile' => '99999999999',
        'otp'     =>'325456',
        'sender' => 'TWILIO_SOURCE_MOBILE_NUMBER'
    );

    // This will send OTP only
    $sms_response = Twilio::message($message_array,$op="otp only", false, true,  false ); // otp

    return response()->json($sms_response,200);
  }
}

After writing the above code in your controller, go to route folder of your project and give the following route in your api.php file.

Route:: post(‘send_sms’,’TwilioTestController@testMessage’);

when you hit the above api, you will get the following Response:

Response Data:

{
   "account_sid": "AC6779d4499d13507f580f37e112a486a2",
   "api_version": "2010-04-01",
   "body": "325456",
   "num_segments": "1",
   "num_media": "1",
   "date_created": "Wed, 18 Aug 2010 20:01:40 +0000",
   "date_sent": null,
   "date_updated": "Wed, 18 Aug 2010 20:01:40 +0000",
   "direction": "outbound-api",
   "error_code": null,
   "error_message": null,
   "from": "+14158141829",
   "price": null,
   "sid": "MM90c6fc909d8504d45ecdb3a3d5b3556e",
   "status": "queued",
   "to": "+15558675310",
   "uri": "/2010-0401/Accounts/AC6779d4499d13507f580f37e112a486a2/Messages/MM90c6fc909d8504d45ecdb3a3d5b3556e.json"
}

NOTE:Trial accounts cannot send messages to unverified numbers; verify +9199XXX23867 at twilio.com/user/account/phone-numbers/verified, or purchase a Twilio number to send messages to unverified numbers.

By developing and consuming api we desicussed above, now you are able to add SMS capabilities to any of your web/mobile apps in minutes.Well I hope this taste of the Twilio API has left you excited to learn even more. To know more about twilio and it’s features visit https://www.twilio.com/. It is fully stocked with examples to help you dive in.

The post SEND SMS USING TWILIO AND LARAVEL appeared first on Welcome to Ahex Technologies.

]]>
2041
How to build RESTful API using Lavavel 5.6 with Mysql https://ahex.co/how-to-build-restful-api-using-lavavel-5-6/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-build-restful-api-using-lavavel-5-6 Sat, 17 Feb 2018 12:40:20 +0000 http://ahex.wpenginepowered.com/?p=1967 In this article we will focus on the following things 1.Basics of RESTful API. 2.Create a new project using laravel 5.6. 3.How to write RESTful APIs. RESTful API REST stands for Representational State Transfer and is an architectural style for network communication between applications, which relies on a stateless protocol (usually HTTP) for interaction. In...

The post How to build RESTful API using Lavavel 5.6 with Mysql appeared first on Welcome to Ahex Technologies.

]]>
In this article we will focus on the following things

1.Basics of RESTful API.

2.Create a new project using laravel 5.6.

3.How to write RESTful APIs.

RESTful API

REST stands for Representational State Transfer and is an architectural style for network communication between applications, which relies on a stateless protocol (usually HTTP) for interaction.

In RESTFUL web service HTTP methods like GET, POST, PUT and DELETE can be used to perform CRUD operations.REST is very simple compare to other methods like SOAP, CORBA, WSDL etc.

Our Services are Data Visualization | Ui/Ux Design

HTTP Methods

In RESTful APIs, we use the HTTP verbs as actions, and the endpoints are the resources acted upon. We will be using the HTTP verbs for their semantic meaning.

  1. GET (Retrieve resource)
  2. POST (Create resource)
  3. PUT (Update resource)
  4. DELETE (Delete resource)

rest

HTTP Status Codes

200 OK
201 Created
304 Not Modified
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
422 Unprocessable Entity
500 Internal Server Error

Installation

Install Laravel by using the Composer in your terminal

step1:$ composer create-project --prefer-dist laravel/laravel rest-api
After successful installation, you should be able to start the server and test if everything is working
step2:$ php artisan serve
Laravel development server started: <http://127.0.0.1:8000>. When you open this url in browser, you should be able to see the following laravel welcome page
Screenshot-2018-2-5 Laravel

create database and update your .env file

we can use the following command to generate database migration along with model

Step3:$ php artisan make:model User -m
It will create app/User.php and database/migrations/2018_02_05_061350_create_users_table.Edit the  User.php,it should look as follows


namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;

/**
 * User
 * 
 * @version 1.0.0
 * @since 1.0.0
 * @author Uday Kumar
 *
 */
class User extends Model
{

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

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
    
    /**
     * Set the user's name.
     *
     * @param  string  $value
     * @return void
     */
    public function setNameAttribute($value)
    {
        return $this->attributes['name'] = ucfirst($value);
    }
    
    /**
     * Set the password
     * 
     * @param string $value
     * @return void
     */
    public function setPasswordAttribute($value)
    {
        return $this->attributes['password'] = Hash::make($value);
    }
}
//end of class User
//end of file User.php

edit your database/migrations/2018_02_05_061350_create_users_table, it should   look like as follows

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

/**
 * CreateUsersTable
 * 
 * @version 1.0.0
 * @since 1.0.0
 * @author Uday Kumar
 *
 */
class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}
//end of class CreateUsersTable
//end of file CreateUsersTable.php
Step4:$ php artisan migrate
Step5:$ php artisan make:request UserRequest edit the Http/requests/UserRequest.php as follows
namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

/**
 * UserRequest
 * 
 * @version 1.0.0
 * @since 1.0.0
 * @author Uday Kumar
 *
 */
class UserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required|max:127|unique:users,name',
            'email' => 'required|email|max:127|unique:users,email',
            'password' => 'required'
        ];
    }
}
//end of class UserRequest
//end of file UserRequest.php


Step6:$ php artisan make:controller UserController –resource edit your Http/Controllers/UserController as follows 
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use Illuminate\Http\Response;
use App\Http\Requests\UserRequest;

/**
 * @access public
 * @author Uday Kumar
 * @version 1.0.0
 */
class UserController extends Controller {
    protected $request;
    protected $user;
    
    /**
     *
     * @param Request $request
     * @param Product $user
     */
    public function __construct(Request $request, User $user) {
        $this->request = $request;
        $this->user = $user;
    }
    
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index() {
        $user = $this->user->all();
        return response()->json(['data' => $user,
            'status' => Response::HTTP_OK]);
    }
    
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(UserRequest $request) {
        $data = $this->request->all();
        $this->user->name = $data['name'];
        $this->user->email = $data['email'];
        $this->user->password = $data['password'];
        $this->user->save();
        
        return response()->json(['status' => Response::HTTP_CREATED]);
    }
    
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update($id) {
        $data = $this->request->all();
        
        $user = $this->user->find($id);
        
        $user->name = $data['name'];
        $user->email = $data['email'];
        $user->password = $data['password'];
        $user->save();
        
        return response()->json(['status' => Response::HTTP_OK]);
    }
    
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id) {
        $user = $this->user->find($id);
        $user->delete();
        
        return response()->json(['status' => Response::HTTP_OK]);
    }
    
}

//end of class UserController
//end of file UserController.php

edit your routes/api.php as follows

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/


Route::resource('user', 'UserController');
Example:
GET
URL:http://127.0.0.1:8000/api/user
Response:
{
  "data": [
    {
      "id": 1,
      "name": "Uday kumar",
      "email": "test@mail.com",
      "created_at": "2018-02-17 07:15:00",
      "updated_at": "2018-02-17 07:18:54"
    }
  ],
  "status": 200
}
//----------------------------------------
POST
URL:http://127.0.0.1:8000/api/user
Request:
{
	"name": "Uday kumar",
	"email": "test@mail.com",
	"password": "xxxxxx"
}
Response:
{
  "status": 201
}

//---------------------------------------
PUT/PATCH
URL:http://127.0.0.1:8000/api/user/1
Request:
{
	"name": "uday kumar",
	"email": "test@mail.com",
	"password": "xxxxxxx"
}
Response:
{
  "status": 200
}

//---------------------------------------
DELETE
URL:http://127.0.0.1:8000/api/user/1
Response:
{
  "status": 200
}

The post How to build RESTful API using Lavavel 5.6 with Mysql appeared first on Welcome to Ahex Technologies.

]]>
1967
How To Send SMS Using Plivo and Laravel https://ahex.co/how-to-send-sms-using-plivo-and-laravel/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-send-sms-using-plivo-and-laravel Sat, 30 Dec 2017 06:00:00 +0000 http://ahex.wpenginepowered.com/?p=1602 Short Message Service (SMS) is a text messaging service component of most telephone, World Wide Web, and mobile device systems. It has achieved huge success in the wireless world. Billions of SMS messages are sent every day. SMS is now a major revenue generator for wireless carriers. A lot of innovative applications are now built...

The post How To Send SMS Using Plivo and Laravel appeared first on Welcome to Ahex Technologies.

]]>
Short Message Service (SMS) is a text messaging service component of most telephone, World Wide Web, and mobile device systems. It has achieved huge success in the wireless world. Billions of SMS messages are sent every day. SMS is now a major revenue generator for wireless carriers. A lot of innovative applications are now built on top of the SMS technology and more are being developed. Many people are turning to short messaging service or SMS messaging as a way to communicate with other individuals instead of making phone calls.

While working on one of the applications being developed on the Laravel framework, I came across a situation where I had to send OTP on user’s mobile phone to verify user mobile number. This could easily be done using plivo. This package enables to send any kind of message to any mobile. So, this blog will provide you information about how to send SMS to any mobile device.

WHAT IS PLIVO

  • Plivo is a Cloud API Platform and a Global Carrier Services Provider for Voice Calls and SMS.
  • Their mission is to simplify global telecom and enable access to quality cloud communications at a low cost. This means that you can add voice calling and SMS text messaging capabilities to any web or mobile app with just a few lines of code.
  • This uses Plivo! API.
  • It requires AuthId and AuthToken, they can be generated by registering @at Plivo after registrion click on Dashboard ,there you will be able to see authid and authtoken.

sample snapshot:
picture

INSTALLATION

To install this package you will need:

  • Laravel 4 or 5
  • PHP

To install via composer run the following command from the terminal.

  • composer require lakshmaji/plivo

LARAVEL INTEGRATION

Once this has finished, you will need to add the service provider to the providers array in your app.php config as follows:

  • LakshmajiPlivoPlivoServiceProvider::class,

Next, also in the app.php config file, under the aliases array, you are required to add the Plivo facade.

  • ‘plivo’ => LakshmajiPlivoFacadePlivo::class,

Finally, you will want to publish the config using the following command:

  • php artisan vendor:publish

In the plivo.php configuration file we need to enter the Plivo API key and ID.

sample snapshot:

Capture

NOTE : Don’t forget to set a auth id and auth secret keys in the config file!, you can get them at Plivo dashboard.

EXAMPLE CODE TO SEND SMS IN PHP

require 'vendor/autoload.php';
use PlivoRestAPI;
$auth_id = "Your AUTH_ID";
$auth_token = "Your AUTH_TOKEN";

$p = new RestAPI($auth_id, $auth_token);

// Set message parameters
$params = array(
        'src' => '1111111111', // Sender's phone number with country code
        'dst' => '2222222222', // Receiver's phone number with country code
        'text' => 'Hi, Message from Plivo', // Your SMS text message
        'url' => 'http://example.com/report/', // The URL to which with the status
          of the message is sent
        'method' => 'POST' // The method used to call the url
       );
// Send message
$response = $p->send_message($params);

// Print the response
echo "Response : ";
print_r ($response['response']);

// Print the Api ID
echo " Api ID : {$response['response']['api_id']}";

// Print the Message UUID
echo "Message UUID : {$response['response']['message_uuid'][0]}";

EXAMPLE CODE TO SEND SMS IN LARAVEL USING CURL

use Plivo;    
public function sendSms()
{    
    $auth_id = "Your AUTH_ID";
    $auth_token = "Your AUTH_TOKEN";

    $src = '1111111111'; //Sender's phone number with country code
    $des = '2222222222'; // Receiver's phone number with country code
    $text = 'Hi, Message from Plivo'; // Your SMS text message
    
    $url = 'http://example.com/report/'; // The URL to which with the status of
           the message is sent
    $data_sms = array("src" => "$src", "dst" => "$dst", "text" => "$text");
    $data_string = json_encode($data_sms);

        $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt(   $ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
            curl_setopt($ch, CURLOPT_USERPWD, $AUTH_ID . ":" . $AUTH_TOKEN);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ch);
        if(!$response){
           die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
          }

        $arr = json_decode($response, true );
        return $arr;

}

The post How To Send SMS Using Plivo and Laravel appeared first on Welcome to Ahex Technologies.

]]>
1602
How to generate Uuid in Laravel https://ahex.co/how-to-generate-uuid-in-laravel/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-generate-uuid-in-laravel Wed, 20 Dec 2017 11:34:00 +0000 http://ahex.wpenginepowered.com/?p=1330 What is Uuid ? It stands for Universal Unique Identifier. As the name suggests, it is used for uniquely identifying a resource over a network. The usage of it in a project has it own set of pros and cons and is debatable, but we will not focus on that currently and will stick to...

The post How to generate Uuid in Laravel appeared first on Welcome to Ahex Technologies.

]]>
What is Uuid ?

It stands for Universal Unique Identifier. As the name suggests, it is used for uniquely identifying a resource over a network. The usage of it in a project has it own set of pros and cons and is debatable, but we will not focus on that currently and will stick to the topic of this blog. You can use it in your project as per your requirements. The Laravel version we are using in this blog is 5.5.

Installing Package

We are going to use webpatser/laravel-uuid package to generate it. Use composer to install this one:

composer require "webpatser/laravel-uuid:^3.0"

Once composer installs it, you will get a message like this one on your screen:

Discovered Package: webpatser/laravel-uuid

Migrations

In Laravel migrations, there is column definition:

$table->uuid('id');

We can use this definition in our migrations to create column to store it.

Creating the Trait

What is trait ?

A “trait” is like an abstract class which means it cannot be instantiated but it contains methods that can be used by other concrete classes. As per definition on php.net

Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of 
single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class 
hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical 
problems associated with multiple inheritance and Mixins.

We are creating a trait so that it becomes less tedious for us to generate the unique identifier with minimum code. So I have created a “traits” folder inside my project. Here is the code for it:

namespace App\Traits;

trait Uuids 
{
    /**
     * 
     */
    protected static function boot()
    {
        parent::boot();
        static::creating(function ($model) {
            $model->{$model->uuid} = 
            str_replace('-', '', \Uuid::generate(4)->string);
        });
    }
}

The static method boot will generate the unique identifier and will assign it to the model attribute that will be used for storing the unique identifier. If you will look closely, we are removing the ‘-‘ from the unique identifier. I removed it because it shortens the length of the Uuid somewhat (saving storage space … ha ha). If you want that then just use “\Uuid::generate(4)->string” method.

Creating the model

A Model class in Laravel is used to interact with the underlaying database table. Usually each table has its own model class. Lets create a model class:

php artisan make:model Models/TestModel

I keep my model class in “Models” folder thats why using “Models/TestModel”, you are free to use your directory. Once this model is created, open the file and initialize the column name that will store the generated unique identifier. For example:

namespace App\Models\TestModel;

use Illuminate\Database\Eloquent\Model;
use App\Traits\Uuids;

class TestModel extends Model
{
    
    use Uuids;
    
    /**
     * Table associated with the model class.
     * 
     * @var string
     */
    protected $table = 'table_name';
    
    /**
     * Attributes that cannot be mass assigned.
     * 
     * @var array
     */
    protected $guarded = ['id'];
    
    /**
     * The attribute to be used for storing the uuids.
     *
     * @var string
     */
    public $uuid = 'project_uuid';
    
}

Now whenever an insert is done using the eloquent for this model, the unique identifier for it is generated and initialized automatically.

Happy Coding

The post How to generate Uuid in Laravel appeared first on Welcome to Ahex Technologies.

]]>
1330