Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Phone Auth Laravel Package

lee-to/laravel-phone-auth

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Prerequisites:

    • Install Livewire: composer require livewire/livewire
    • Install Doctrine DBAL: composer require doctrine/dbal
  2. Install Package:

    composer require lee-to/laravel-phone-auth
    php artisan vendor:publish --provider="Leeto\PhoneAuth\Providers\PhoneAuthServiceProvider"
    
    • Publish the config file (config/phone_auth.php) and update as needed.
  3. User Model Setup:

    • Add the PhoneVerification trait and PhoneCast to your User model:
      use Leeto\PhoneAuth\Traits\PhoneVerification;
      use Leeto\PhoneAuth\Casts\PhoneCast;
      
      protected $casts = [
          'phone' => PhoneCast::class,
      ];
      
  4. First Use Case:

    • Include the Livewire component in your blade view for phone verification:
      @livewire('phone-verification')
      
    • This renders a phone verification form with Tailwind CSS classes by default.

Implementation Patterns

Workflows

Basic Phone Verification Flow

  1. User Input:

    • The @livewire('phone-verification') component renders a form where users input their phone number.
    • The package handles phone number formatting via the PhoneCast.
  2. OTP Generation and Delivery:

    • The package generates a One-Time Password (OTP) and sends it via SMS (ensure you configure a gateway like Twilio, AWS SNS, or another SMS provider in config/phone_auth.php).
    • Example config snippet:
      'sms' => [
          'provider' => 'twilio',
          'twilio' => [
              'sid' => env('TWILIO_SID'),
              'token' => env('TWILIO_TOKEN'),
              'from' => env('TWILIO_FROM'),
          ],
      ],
      
  3. OTP Verification:

    • After submitting the phone number, the user receives an OTP.
    • The user inputs the OTP in the verification step, which is handled automatically by the Livewire component.
  4. Post-Verification Actions:

    • Upon successful verification, the user is marked as phone-verified in the database.
    • Redirect users based on the customRedirectTo property or default config.

Login and Registration Integration

  • Use the loginAndRegister property to allow users to either log in (if their phone is already verified) or register (if not):
    @livewire('phone-verification', ['loginAndRegister' => true])
    

Customizing the Verification Process

  • Custom Fields:

    • Disable default fields with emptyCustomFields:
      @livewire('phone-verification', ['emptyCustomFields' => true])
      
    • Pass custom parameters to the view:
      @livewire('phone-verification', [
          'customParams' => [
              'btn' => 'Verify My Number',
              'title' => 'Phone Verification',
          ]
      ])
      
  • Event Handling:

    • Disable event emissions (e.g., emitBefore, emitAfter) with stopEvents:
      @livewire('phone-verification', ['stopEvents' => true])
      
  • Redirect Logic:

    • Override the default redirect path:
      @livewire('phone-verification', ['customRedirectTo' => '/dashboard'])
      

Integration Tips

  1. Livewire Hooks:

    • Extend functionality using Livewire hooks. For example, listen for the verified event to trigger additional logic:
      Livewire::hook('phone.verified', function ($user) {
          // Custom logic after verification
      });
      
  2. Database Schema:

    • Ensure your users table has a phone column (e.g., phone_number or phone). The PhoneCast handles formatting, but the column should store raw numbers (e.g., 1234567890).
  3. Testing:

    • Mock SMS services during testing. Use Laravel’s fake method for SMS:
      $this->fake();
      $this->actingAs($user);
      $response = $this->post('/verify-phone', ['phone' => '1234567890']);
      
  4. Multi-Language Support:

    • Customize SMS templates in config/phone_auth.php to support multiple languages:
      'sms' => [
          'templates' => [
              'en' => 'Your verification code is {code}.',
              'es' => 'Su código de verificación es {code}.',
          ],
      ],
      
  5. Rate Limiting:

    • Implement rate limiting for OTP requests to prevent abuse. Use Laravel’s throttle middleware or a package like spatie/rate-limiter.

Gotchas and Tips

Pitfalls

  1. SMS Provider Configuration:

    • Forgetting to configure the SMS provider in config/phone_auth.php will result in silent failures. Always verify your provider settings (e.g., Twilio credentials, AWS keys).
    • Debug Tip: Check Laravel logs for SMS-related errors if verification codes aren’t being sent.
  2. Phone Number Format:

    • The PhoneCast expects raw phone numbers (e.g., 1234567890). Storing formatted numbers (e.g., +1 (123) 456-7890) may cause issues during verification.
    • Fix: Ensure your database column stores unformatted numbers and let the cast handle formatting.
  3. Livewire Component Caching:

    • If you customize the phone-verification component’s view, clear Livewire’s view cache:
      php artisan livewire:discover
      
  4. User Model Not Updated:

    • Forgetting to add the PhoneVerification trait or PhoneCast to your User model will break phone verification functionality.
    • Debug Tip: Verify the trait and cast are included by checking the User model’s uses and casts properties.
  5. OTP Expiry:

    • The package does not handle OTP expiry by default. Ensure your SMS provider’s OTPs expire after a reasonable time (e.g., 5–10 minutes).
    • Workaround: Implement a verified_at column in your users table and validate OTPs against this timestamp.
  6. Tailwind CSS Dependencies:

    • The default template uses Tailwind CSS classes. If your project doesn’t use Tailwind, customize the view or install Tailwind to avoid styling issues.

Debugging

  1. Log OTPs:

    • Enable logging for OTP generation and verification in config/phone_auth.php:
      'debug' => [
          'log_otp' => true,
      ],
      
    • Check storage/logs/laravel.log for OTP details.
  2. Verify Webhook Responses:

    • If using a custom SMS provider, ensure webhook responses are properly handled. Log the response from your SMS provider to debug issues:
      \Log::info('SMS Provider Response', ['response' => $response]);
      
  3. Database Conflicts:

    • If users report duplicate OTPs or verification failures, check for duplicate phone entries in the users table or conflicts in the confirmed_phones table (created by the ConfirmedPhone model).
  4. Livewire Wire:ignore:

    • If the phone input field isn’t updating dynamically, ensure the input isn’t wrapped in wire:ignore. The component expects dynamic updates.

Extension Points

  1. Custom SMS Providers:

    • Extend the package by adding support for custom SMS providers. Override the Leeto\PhoneAuth\Services\SmsService class or bind a custom implementation in the service provider:
      $this->app->bind(
          \Leeto\PhoneAuth\Contracts\SmsService::class,
          \App\Services\CustomSmsService::class
      );
      
  2. Custom Verification Logic:

    • Override the verification logic by extending the PhoneVerification trait or the PhoneVerificationController:
      namespace App\Traits;
      use Leeto\PhoneAuth\Traits\PhoneVerification as BasePhoneVerification;
      
      trait PhoneVerification extends BasePhoneVerification {
          public function verifyPhone($otp) {
              // Custom verification logic
          }
      }
      
  3. Event Listeners:

    • Listen to package events to trigger custom actions. Available events include:
      • phone.verified: Triggered after successful verification.
      • phone.verification.failed: Triggered on verification failure.
    • Example listener:
      use Leeto\PhoneAuth\Events\PhoneVerified;
      
      PhoneVerified::listen(function (PhoneVerified $event) {
          // Send welcome email or notify admin
      });
      
  4. Custom Templates:

    • Override the default Blade templates by publishing and customizing them:
      php artisan vendor:publish --tag=phone-auth-views
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope