This package provides convenient methods for making token code, sending and verifying mobile phone verification requests.

Overview

Laravel Mobile Verification

alt text

Test Status Coverage Status Code Style Status Latest Stable Version Total Downloads License

Introduction

Many web applications require users to verify their mobile phone numbers before using the application. Rather than forcing you to re-implement this on each application, this package provides convenient methods for sending and verifying mobile phone verification requests.

Installation

You can install the package via composer:

composer require fouladgar/laravel-mobile-verification

Laravel 5.5 uses Package Auto-Discovery, so you are not required to add ServiceProvider manually.

Configuration

To get started, you should publish the config/mobile_verifier.php config file with:

php artisan vendor:publish --provider="Fouladgar\MobileVerification\ServiceProvider" --tag="config"

Token Storage

After generating a token, we need to store it in a storage. This package supports two drivers: cache and database which the default driver is cache. You may specify which storage driver you would like to be used for saving tokens in your application:

'cache', ]; ">
// config/mobile_verifier.php



return [
    /**
    |Supported drivers: "cache", "database"
    */
    'token_storage' => 'cache',
];
Database

It means after migrating, a table will be created which your application needs to store verification tokens.

If you’re using another table name for users table or different column name for mobile phone or even mobile_verification_tokens table, you can customize their values in config file:

// config/mobile_verifier.php



return [

    'user_table'    => 'users',
    
    'mobile_column' => 'mobile',
    
    'token_table'   => 'mobile_verification_tokens',

    //...
];
Cache

When using the cache driver, the token will be stored in a cache driver configured by your application. In this case, your application performance is more than when using database definitely.

All right! Now you should migrate the database:

php artisan migrate

Depending on the token_storage config, the package migration will create a token table. Also, a mobile_verified_at and mobile column will be added to your users table to show user verification state and store user's mobile phone.

Model Preparation

In the following, make sure your User model implements the Fouladgar\MobileVerification\Contracts\MustVerifyMobile contract and use the Fouladgar\MobileVerification\Concerns\MustVerifyMobile trait:



namespace App;

use Fouladgar\MobileVerification\Contracts\MustVerifyMobile as IMustVerifyMobile;
use Fouladgar\MobileVerification\Concerns\MustVerifyMobile;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable implements IMustVerifyMobile
{
    use Notifiable, MustVerifyMobile;

    // ...
}

SMS Client

You can use any SMS service for sending verification messages(it depends on your choice). For sending notifications via this package, first you need to implement the Fouladgar\MobileVerification\Contracts\SMSClient contract. This contract requires you to implement sendMessage method.

This method will return your SMS service API results via a Payload object which contains user number and token message:



namespace App;

use Fouladgar\MobileVerification\Contracts\SMSClient;
use Fouladgar\MobileVerification\Notifications\Messages\Payload;

class SampleSMSClient implements SMSClient
{
    protected $SMSService;

    /**
     * @param Payload $payload
     *
     * @return mixed
     */
    public function sendMessage(Payload $payload)
    {
        // preparing SMSService ...

        return $this->SMSService
                 ->send($payload->getTo(), $payload->getToken());
    }

    // ...
}

In above example, SMSService can be replaced with your chosen SMS service along with its respective method.

Next, you should set the your SMSClient class in config file:

// config/mobile_verifier.php



return [

  'sms_client' => App\SampleSMSClient::class, 
    
  //...
];

Usage

Now you are ready for sending a verification message! You just need to dispatch the Illuminate\Auth\Events\Registered event after registering user:



use Illuminate\Auth\Events\Registered;

// Register user

 event(new Registered($user));

//...

At this point, a notification message has been sent to user automatically, and you've done half of the job!

Routing

This package includes the Fouladgar\MobileVerification\Http\Controllers\MobileVerificationController class that contains the necessary logic to send verification token and verify users.

Verify

In order to use this route, you should send token message of an authenticated user (along with any desired data) to this route /auth/mobile/verify:

curl -X POST \
      http://example.com/auth/mobile/verify \
      -H 'Accept: application/json' \
      -H 'Authorization: JWT_TOKEN' \
      -F token=12345

Resend

If you need to resend a verification message, you can use this route /auth/mobile/resend for an authenticated user:

curl -X POST \
      http://example.com/auth/mobile/resend \
      -H 'Accept: application/json' \
      -H 'Authorization: JWT_TOKEN'

Notice: You should choose a long with middleware which you are going to use them for above APIs through set it in config file:

// config/mobile_verifier.php



return [

    'middleware' => ['auth:sanctum'],

    //...
];

Customize Routes and Controller

In order to change default routes prefix or routes themselves, you can customize them in config file:

// config/mobile_verifier.php



return [

    'routes_prefix' => 'auth',

    'routes' => [
        'verify' => '/mobile/verify',
        'resend' => '/mobile/resend',
    ],

    //...
];

Also, this package allows you to override default controller. To achieve this, you can extend your controller from Fouladgar\MobileVerification\Http\Controllers\BaseVerificationController and set your controller namespace in config file:

// config/mobile_verifier.php



return [

    'controller_namespace' => 'App\Http\Controllers',

    //...
];

Note: You can only change controller namespace and name of the controller should remain as package default controller (MobileVerificationController)



namespace App\Http\Controllers;

use Fouladgar\MobileVerification\Http\Controllers\BaseVerificationController;

class MobileVerificationController extends BaseVerificationController
{
    /**
     * Where to redirect users after verification.
     *
     * @var string
     */
    protected $redirectTo = '/home';
}

Important note: If you set header request to Accept:application/json, the response will be in Json format, otherwise the user will automatically be redirected to /home. You can customize the post verification redirect location by defining a redirectTo method or property on the MobileVerificationController.

Protecting Routes

Route middleware can be used to only allow verified users to access a given route. This package ships with a verified middleware, which is defined at Fouladgar\MobileVerification\Http\Middleware. Since this middleware is already registered in your application's HTTP kernel, all you need to do is attach the middleware to a route definition:

Route::get('profile', function () {
    // Only verified users may enter...
})->middleware('mobile.verified');

Using Queue

By default, this package does not process sending verification messages in the queue. But if you want your sending messages to be queued, you may change connection value from sync to your preferred queue connection. And be sure to config your queue connection in your .env file. You are allowed to to change other queue settings here in the config.

[ 'connection' => 'sync', 'queue' => 'default', 'tries' => 3, 'timeout' => 60, ] ]; ">
// config/mobile_verifier.php


return [
     /**
     | Supported drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
     */
    'queue' =>  [
       'connection' => 'sync',
       'queue' => 'default',
       'tries' => 3,
       'timeout' => 60,
    ]
];

Translates and Views

To publish translation file you may use this command:

php artisan vendor:publish --provider="Fouladgar\MobileVerification\ServiceProvider" --tag="lang"

If you are not using AJAX requests, you should have some views which we provided you some information through session variables. In case of errors, you just need to use laravel default $errors variable. In case of successful verification, you can use mobileVerificationVerified variable and for successful resend verification you may use mobileVerificationResend variable. These variables contain messages which you can customize in provided language file:

// lang/vendor/MobileVerification/en/mobile_verification.php



return [
    'successful_verification' => 'Your mobile has been verified successfully.',
    'successful_resend'       => 'The token has been resent successfully.',
    'already_verified'        => 'Your mobile already has been verified.',
    //etc...
];

Event

This package dispatch an event during the mobile verification process. You may attach listeners to this event in your EventServiceProvider:

/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    'Fouladgar\MobileVerification\Events\Verified' => [
        'App\Listeners\LogVerifiedUser',
    ],
];

Testing

composer test

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

License

Laravel-Mobile-Verification is released under the MIT License. See the bundled LICENSE file for details.

Built with ❤️ for you.

Comments
  • Send SMS Manually

    Send SMS Manually

    Hi, Thanks for providing this package. Can you provide a sample code about how to send a verification sms manually not only in case of user registration? To make it clear, i wanna to send sms code notification on every user login attempt.

    opened by alr2413 13
  •  syntax error, unexpected 'verify' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST)

    syntax error, unexpected 'verify' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST)

    using laravel 7.5.2 and php 7.2.29

    ::Composer\Autoload\includeFile D:******\vendor\fouladgar\laravel-mobile-verification\src\Http\Controllers\MobileVerificationController.php:25 / |-------------------------------------------------------------------------- | Mobile Verification Controller | This controller is responsible for handling mobile verification for any | user that recently registered with the application. Tokens may also | be re-sent if the user didn't receive the original token message.

    protected $redirectTo = '/home';
    public verify()
    

    { ....... verify code ( check database ... }

    invalid 
    opened by saeed7m 8
  • Livewire Implementation

    Livewire Implementation

    This package has a good documentation with laravel implementation but I really want to change components to livewire. I can not find any easy way of doing that. Can someone please give me an idea about this?

    opened by beneyraheem 7
  • Verified issue

    Verified issue

    Hi,

    I managed to make it work, it works flawlessly, with my own VueJS SPA, sanctum as the auth, etc.

    The only trouble I have is that once I verified the token, the user is not refreshed until the next login. Is this normal? I can't find a way to do it without forcing something.

    Thank you

    opened by arebuffo 6
  • custom redirect for resend and verify

    custom redirect for resend and verify

    How can I differentiate between verify and resend redirect To ? for example after verified mobile redirect to home and after resend stay on verify form to get new code ?

    help wanted 
    opened by saeed7m 5
  • check when was the last code sent to current user

    check when was the last code sent to current user

    Firstly, congrats on creating a functional and complete as well as generic-enough package. I was wondering if there is a way of checking when was the last time we sent code to a user? I'm using default settings of the package (cache driver, no mobile_verification_tokens `table).

    opened by Shujee 4
  • Undefined property: Fouladgar\MobileVerification\Notifications\Messages\Payload::$getToken

    Undefined property: Fouladgar\MobileVerification\Notifications\Messages\Payload::$getToken

    Can you please explain more about this? where can i use this code ?which file ?

    use Illuminate\Auth\Events\Registered; // Register user event(new Registered($user)); //...

    I have this error and think that it may be related to this

    Undefined property: Fouladgar\MobileVerification\Notifications\Messages\Payload::$getToken

    I'm new to laravel ,,, sorry

    opened by saeed7m 4
  • Duplication of migrations on publish

    Duplication of migrations on publish

    I had encountered this error on migrations after publishing package

    Illuminate\Database\QueryException 
    
      SQLSTATE[HY000]: General error: 1 table "mobile_verification_tokens" already exists (SQL: create table "mobile_verification_tokens" ())
    
      at vendor/laravel/framework/src/Illuminate/Database/Connection.php:742
        738▕         // If an exception occurs when attempting to run a query, we'll format the error
        739▕         // message to include the bindings with SQL, which will make this exception a
        740▕         // lot more helpful to the developer instead of just the database's errors.
        741▕         catch (Exception $e) {
      ➜ 742▕             throw new QueryException(
        743▕                 $query, $this->prepareBindings($bindings), $e
        744▕             );
        745▕         }
        746▕     }
    
    opened by MANKolahi 3
  • Forcing the user to confirm the mobile before logging in and using the site

    Forcing the user to confirm the mobile before logging in and using the site

    Thanks for the great package! Do you have a sample code for VIEW and Routing that guides in such a way that the user is directed to the page immediately after registration to enter the code sent to his mobile phone, and if it is not correct, he is prevented from accessing his profile pages and maybe requests code again?

    thank you .

    question 
    opened by saeed7m 3
  • Base table or view already exists

    Base table or view already exists

    When I installed this plugin, there was an error with AddSentAtInTokensTable. We already have the table, we just need to update it.

    Schema::create($this->tokenTable, function (Blueprint $table) { $table->timestamp('sent_at')->nullable(); });

    should be replaced by 

    Schema::table($this->tokenTable, function (Blueprint $table) { $table->timestamp('sent_at')->nullable(); });

    opened by AkikiCharbel 2
  • Integration with Laravel Socialite and Laravel Fortify (Login)

    Integration with Laravel Socialite and Laravel Fortify (Login)

    Have encountered an issue related to this.

    I am using both Laravel Socialite and Laravel Fortify to authenticate my users.

    Registration in Laravel Fortify has integrated perfectly with this Package, but Login has (if I can call it) a loop hole. When I attempt to Login a user whose Mobile is not Verified, the browser returns a "too many redirects" error.

    The same case happens to Laravel Socialite. Socialite does not provide the system with a user's mobile number, I have to fetch it directly from the user using a form. Adding a form that fetches this info and sending it to the route "mobile.verify" does not do anything. It directs to Home and then returns the 'too many redirects" error.

    Perhaps:

    1. If the package could have a fall back route for when a user is not verified it would fix the too many redirects issue.
    2. If the package could point out a dedicated view for which users can manually enter their mobile numbers and send it to a specific controller, one that Validates then triggers the event(new Registered($user)); Event, it would work for even users logged in via Laravel Socialite.

    Kindly, let me know your thoughts.

    Originally posted by @thedanmwangi in https://github.com/mohammad-fouladgar/laravel-mobile-verification/issues/27#issuecomment-1100744236

    opened by thedanmwangi 2
Owner
M.Fouladgar
sᴏғᴛᴡᴀʀᴇ ᴅᴇᴠᴇʟᴏᴘᴇʀ
M.Fouladgar
This package adds support for verifying new email addresses: when a user updates its email address, it won't replace the old one until the new one is verified.

Laravel Verify New Email Laravel supports verifying email addresses out of the box. This package adds support for verifying new email addresses. When

Protone Media 300 Dec 30, 2022
A convenient helper for using the laravel-seo package with Filament Admin and Forms

Combine the power of Laravel SEO and Filament PHP. This package is a convenient helper for using the laravel-seo package with Filament Admin and Forms

Ralph J. Smit 39 Dec 21, 2022
Localization Helper - Package for convenient work with Laravel's localization features and fast language files generation

Localization Helper Package for convenient work with Laravel's localization features and fast language files generation. Installation Via Composer $ c

Galymzhan Begimov 0 Jul 13, 2019
Example of using TALL stack to select country phone code.

Select country phone code using TALL stack About Example of using TALL stack to select country phone code. Each item represents a country. Each item h

Fernando Chagas 3 Jul 27, 2022
Provides email verification on the go.

Email Checker Email Checker was created and maintained by Aman Nurani. It provides a powerful email validating system for both development and product

Aman 137 Dec 23, 2022
An opinionated support package for Laravel, that provides flexible and reusable helper methods and traits for commonly used functionality.

Support An opinionated support package for Laravel, that provides flexible and reusable helper methods and traits for commonly used functionality. Ins

Ian Olson 3 Apr 14, 2021
A package for Myanmar Font, Phone and other Myanmar tools using Laravel Macro

Laravel Myanmar Tools A package for Myanmar Font, Phone and other Myanmar tools using Laravel Macro. Installation composer require pyaesoneaung/larave

Pyae Sone Aung 22 Dec 20, 2022
Convenient tool for speeding up the intern/officer review process.

icpc-app-screen Convenient tool for speeding up the intern/officer applicant review process. Eliminates the pain from reading application responses of

null 1 Oct 30, 2021
A convenient way to initialize your application

A convenient way to initialize your application. Introduction We all know, that every application should contain readme file and Installation section

Mad Web 684 Dec 16, 2022
Laravel 2-Step Verification is a package to add 2-Step user authentication to any Laravel project easily.

Laravel 2-Step verification is a package to add 2-Step user authentication to any Laravel project easily. It is configurable and customizable. It uses notifications to send the user an email with a 4-digit verification code. Laravel 2-Step Authentication Verification for Laravel. Can be used in out the box with Laravel's authentication scaffolding or integrated into other projects.

Jeremy Kenedy 204 Dec 23, 2022
Phone number functionality for Laravel

Laravel Phone Adds phone number functionality to Laravel and Lumen based on the PHP port of Google's libphonenumber API by giggsey. Table of Contents

null 2.1k Dec 31, 2022
Laravel Dutch Phone Number Validator

Laravel Dutch Phone Number Validator Validate if the given phone number is a valid Dutch phone number Table of Contents Installation Usage Translation

Tim Wassenburg 0 May 30, 2022
Adds phone number functionality to Laravel based on the PHP port of Google's libphonenumber API by giggsey.

Laravel Phone Adds phone number functionality to Laravel based on the PHP port of Google's libphonenumber API by giggsey. Table of Contents Demo Insta

null 2.1k Jan 2, 2023
Adds phone number functionality to TYPO3 based on the PHP port of Google's libphonenumber API by giggsey

TYPO3 Phone Adds phone number functionality to TYPO3 based on the PHP port of Google's libphonenumber API by giggsey. Installation composer require si

Simon Schaufelberger 3 Oct 25, 2022
A Laravel package making a diagram of your models, relations and the ability to build them with it

Laravel Schematics This package allows you to make multiple diagrams of your Eloquent models and their relations. It will help building them providing

Maarten Tolhuijs 1.4k Dec 31, 2022
🔐 JSON Web Token Authentication for Laravel & Lumen

Documentation Documentation for 1.* here For version 0.5.* See the WIKI for documentation. Supported by Auth0 If you want to easily add secure authent

Sean Tymon 10.7k Jan 3, 2023
Source code behind the Laracasts Larabit: My Favorite Laravel Collections Methods

My Favorite Laravel Collections Methods This is the source code behind the Laracasts Larabit: My Favorite Laravel Collections Methods, and features al

Andrew Schmelyun 2 Dec 2, 2021
Laravel-FCM is an easy to use package working with both Laravel and Lumen for sending push notification with Firebase Cloud Messaging (FCM).

Laravel-FCM Introduction Laravel-FCM is an easy to use package working with both Laravel and Lumen for sending push notification with Firebase Cloud M

Rahul Thapa 2 Oct 16, 2022
User authentication REST API with Laravel (Register, Email verification, Login, Logout, Logged user data, Change password, Reset password)

User Authentication API with Laravel This project is a user authentication REST API application that I developed by using Laravel and MySql. Setup Fir

Yusuf Ziya YILDIRIM 3 Aug 23, 2022