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 Bangla Text Converter Laravel Package

nanopkg/laravel-bangla-text-converter

Laravel package to convert Bengali text between Unicode and Bijoy encodings. Use the BanglaTextConverter facade to quickly transform strings (toBijoy/toUnicode) in your app, with simple Composer install and test support.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require nanopkg/laravel-bangla-text-converter
    

    The package auto-registers via Laravel's service provider.

  2. First Use Case: Convert Unicode Bengali text to Bijoy format in a controller or blade template:

    use Nanopkg\BanglaTextConverter\Facades\BanglaTextConverter;
    
    $unicodeText = 'আমি বাংলায় লিখছি';
    $bijoyText = BanglaTextConverter::toBijoy($unicodeText);
    

    Or convert Bijoy back to Unicode:

    $bijoyText = 'Avmi evgla‡v lixvi';
    $unicodeText = BanglaTextConverter::toUnicode($bijoyText);
    
  3. Where to Look First:

    • Facade: Nanopkg\BanglaTextConverter\Facades\BanglaTextConverter
    • Service Provider: Nanopkg\BanglaTextConverter\BanglaTextConverterServiceProvider
    • Helper Methods: toBijoy() and toUnicode()

Implementation Patterns

Common Workflows

  1. Form Handling:

    // In a FormRequest or controller
    public function store(Request $request) {
        $request->validate(['bangla_text' => 'required']);
        $convertedText = BanglaTextConverter::toUnicode($request->bangla_text);
        // Save $convertedText to database
    }
    
  2. Blade Templates:

    @php
        $bijoyText = BanglaTextConverter::toBijoy('আমার সোনার বাংলা');
    @endphp
    <textarea>{{ $bijoyText }}</textarea>
    
  3. Database Storage:

    // Store Bijoy format in DB for legacy systems
    $user->bangla_bio = BanglaTextConverter::toBijoy($request->bio);
    $user->save();
    
  4. Middleware for Automatic Conversion:

    // app/Http/Middleware/ConvertBanglaText.php
    public function handle($request, Closure $next) {
        if ($request->has('bangla_text')) {
            $request->merge([
                'bangla_text' => BanglaTextConverter::toUnicode($request->bangla_text)
            ]);
        }
        return $next($request);
    }
    
  5. API Responses:

    return response()->json([
        'unicode_text' => BanglaTextConverter::toUnicode($request->bijoy_text),
        'bijoy_text' => BanglaTextConverter::toBijoy($request->unicode_text)
    ]);
    

Integration Tips

  • Validation:

    use Illuminate\Validation\Rule;
    
    $validator = Validator::make($request->all(), [
        'bangla_text' => [
            'required',
            Rule::unique('posts')->ignore($post->id),
            function ($attribute, $value, $fail) {
                if (strlen(BanglaTextConverter::toUnicode($value)) > 500) {
                    $fail('The bangla text may be too long.');
                }
            }
        ]
    ]);
    
  • Eloquent Accessors/Mutators:

    // In User model
    public function getBanglaNameAttribute($value) {
        return BanglaTextConverter::toUnicode($value);
    }
    
    public function setBanglaNameAttribute($value) {
        $this->attributes['bangla_name'] = BanglaTextConverter::toBijoy($value);
    }
    
  • Artisan Command:

    // Convert all records in a table
    public function handle() {
        DB::table('posts')->whereNotNull('bangla_content')
            ->update(['bangla_content' => BanglaTextConverter::toUnicode(DB::raw('bangla_content'))]);
    }
    

Gotchas and Tips

Pitfalls

  1. Character Encoding Issues:

    • Ensure your database and application use UTF-8 encoding. Bijoy/Bangla conversion relies on proper character handling.
    • Fix: Add this to your .env:
      DB_CONNECTION=mysql
      DB_CHARSET=utf8mb4
      DB_COLLATION=utf8mb4_unicode_ci
      
  2. Partial Conversions:

    • The converter may fail on mixed scripts (e.g., English + Bengali). Validate input before conversion.
    • Tip: Use regex to check for Bengali characters first:
      if (preg_match('/[\x{0980}-\x{09FF}]/u', $text)) {
          // Proceed with conversion
      }
      
  3. Performance with Large Texts:

    • Converting very long texts (e.g., books) may time out. Process in chunks.
    • Tip: Use Laravel queues for batch processing:
      ConvertBanglaJob::dispatch($largeText)->onQueue('bangla');
      
  4. Facade Caching:

    • The facade caches the converter instance. Clear cache if you extend the converter:
      php artisan cache:clear
      

Debugging

  1. Invalid Output:

    • Check for non-Bengali characters in input. The converter may produce garbled output if fed mixed scripts.
    • Debug Tip: Log raw input/output:
      \Log::debug('Input:', ['text' => $inputText, 'converted' => $outputText]);
      
  2. Case Sensitivity:

    • Bijoy conversion is case-sensitive. Ensure your input matches expected formats (e.g., Avmi vs avmi).
  3. Special Characters:

    • Punctuation and symbols may not convert perfectly. Test edge cases like:
      $text = 'আমি ১০০ টাকা খাই।';
      

Extension Points

  1. Custom Conversion Rules:

    • Extend the converter by publishing and modifying the config:
      php artisan vendor:publish --tag=bangla-text-converter-config
      
    • Add custom mappings in config/bangla-text-converter.php:
      'custom_mappings' => [
          'special_symbol' => 'বিশেষ_সিম্বল',
      ],
      
  2. Service Provider Binding:

    • Override the converter binding in your AppServiceProvider:
      public function register() {
          $this->app->bind(\Nanopkg\BanglaTextConverter\Contracts\BanglaConverter::class, function () {
              return new \App\Services\CustomBanglaConverter();
          });
      }
      
  3. Testing:

    • Mock the converter in tests:
      $this->app->instance(
          \Nanopkg\BanglaTextConverter\Contracts\BanglaConverter::class,
          Mockery::mock(\Nanopkg\BanglaTextConverter\Contracts\BanglaConverter::class)
      );
      

Configuration Quirks

  1. Default Conversion Direction:

    • The package defaults to no automatic conversion. Always explicitly call toBijoy() or toUnicode().
  2. Environment-Specific Settings:

    • Use environment variables to toggle conversion behavior:
      if (env('BANGLA_AUTO_CONVERT', false)) {
          $text = BanglaTextConverter::toUnicode($request->input);
      }
      
  3. Localization:

    • The converter does not handle locale-specific formatting (e.g., numbers, dates). Use Laravel's localization helpers separately.

Pro Tips

  1. Batch Processing:

    // Convert all records in a table using Laravel's chunk
    DB::table('articles')->whereNotNull('bangla_content')
        ->chunk(200, function ($records) {
            foreach ($records as $record) {
                $record->update([
                    'bangla_content' => BanglaTextConverter::toUnicode($record->bangla_content)
                ]);
            }
        });
    
  2. API Versioning:

    • Maintain backward compatibility by versioning your API endpoints:
      // v1 uses Bijoy, v2 uses Unicode
      Route::prefix('v2')->group(function () {
          Route::post('/articles', [ArticleController::class, 'storeUnicode']);
      });
      
  3. User Preferences:

    • Store user preferences for text format (Bijoy/Unicode) in the database:
      $user->preferred_bangla_format = $request->format; // 'bijoy' or 'unicode'
      $user->save();
      
    • Then apply dynamically:
      $format = auth()->user()->preferred_bangla_format ?? 'unicode';
      $text = $format === 'bijoy' ? BanglaTextConverter::toBijoy($text) : $text;
      
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.
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
anil/file-picker
broqit/fields-ai