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

Short Code Laravel Package

adrianbaez/short-code

Laravel package for defining and parsing short codes (e.g., [tag param="value"]) in strings, letting you register handlers and render dynamic content in text fields, emails, or CMS-like pages with simple, reusable placeholders.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require adrianbaez/short-code
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        Adrianbaez\ShortCode\ShortCodeServiceProvider::class,
    ],
    
  2. Basic Usage Decode a short code in a controller or Blade view:

    use Adrianbaez\ShortCode\Facades\ShortCode;
    
    $decoded = ShortCode::decode('ABC123');
    
  3. First Use Case Replace a URL shortener or obfuscate IDs in URLs:

    $shortCode = ShortCode::encode(12345); // Generates a short code like "ABC123"
    $original = ShortCode::decode($shortCode); // Returns 12345
    

Implementation Patterns

Core Workflows

  1. Encoding/Decoding IDs

    // Encode an integer ID
    $shortCode = ShortCode::encode(999999);
    
    // Decode back to original
    $originalId = ShortCode::decode($shortCode);
    
  2. Custom Alphabets Override the default alphabet (A-Z, 0-9) via config:

    // config/short-code.php
    'alphabet' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
    
  3. Blade Integration

    @php
        $shortCode = \Adrianbaez\ShortCode\Facades\ShortCode::encode($post->id);
    @endphp
    <a href="{{ route('post.show', $shortCode) }}">Read More</a>
    
  4. Middleware for URL Routing

    // In a route middleware
    public function handle($request, Closure $next) {
        $id = ShortCode::decode($request->route('short_code'));
        $request->merge(['id' => $id]);
        return $next($request);
    }
    

Advanced Patterns

  • Batch Processing

    $ids = [1, 2, 3, 4];
    $shortCodes = ShortCode::batchEncode($ids);
    
  • Validation

    use Adrianbaez\ShortCode\Rules\ValidShortCode;
    
    $request->validate([
        'code' => ['required', new ValidShortCode],
    ]);
    

Gotchas and Tips

Common Pitfalls

  1. Collision Risk

    • The package uses a base-36 encoding (A-Z, 0-9). For IDs > 1,679,615, collisions become likely.
    • Fix: Use a larger alphabet (e.g., include lowercase letters) or prepend a checksum.
  2. Non-Integer Inputs

    • The decoder expects integers. Passing strings/arrays will fail silently.
    • Fix: Validate input:
      if (!is_numeric($shortCode)) {
          throw new \InvalidArgumentException('Invalid short code');
      }
      
  3. URL-Friendly Constraints

    • Default alphabet excludes /, :, or ?, which may break URL routing.
    • Fix: Extend the alphabet or sanitize:
      $urlSafeCode = str_replace(['/', '?'], '', $shortCode);
      
  4. Performance with Large Datasets

    • Decoding millions of codes in a loop is slow. Cache results:
      $cacheKey = 'short_code_'.$shortCode;
      $original = cache()->remember($cacheKey, now()->addHours(1), function() use ($shortCode) {
          return ShortCode::decode($shortCode);
      });
      

Debugging Tips

  • Check Alphabet Length If decoding fails, verify config/short-code.php:

    'alphabet_length' => strlen(config('short-code.alphabet')) // Must be >= 36 for base-36
    
  • Log Invalid Codes Wrap decodes in a try-catch:

    try {
        $id = ShortCode::decode($code);
    } catch (\Exception $e) {
        \Log::warning("Failed to decode {$code}: {$e->getMessage()}");
    }
    

Extension Points

  1. Custom Decoders Bind a custom decoder in the service provider:

    $this->app->bind('short-code.decoder', function() {
        return new \App\Services\CustomShortCodeDecoder();
    });
    
  2. Event Hooks Listen for encoding/decoding events (if the package supports them):

    ShortCode::encoded(function($shortCode, $original) {
        // Log or process encoded codes
    });
    
  3. Database Storage Store short codes in a short_codes table with a mapping column:

    // Example migration
    Schema::create('short_codes', function (Blueprint $table) {
        $table->string('code')->unique();
        $table->integer('mapping');
        $table->timestamps();
    });
    
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.
cadot.eu/make
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky