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 Url Laravel Package

ashallendesign/short-url

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require ashallendesign/short-url
    php artisan vendor:publish --provider="AshAllenDesign\ShortUrl\ShortUrlServiceProvider" --tag="migrations"
    php artisan vendor:publish --provider="AshAllenDesign\ShortUrl\ShortUrlServiceProvider" --tag="config"
    php artisan migrate
    
  2. First Use Case: Generate a short URL from a long URL:

    use AshAllenDesign\ShortUrl\Facades\ShortUrl;
    
    $shortUrl = ShortUrl::create('https://example.com/long-url');
    echo $shortUrl->short; // Outputs: e.g., "https://yourdomain.com/abc123"
    
  3. Key Files to Review:

    • config/short-url.php (for customization)
    • database/migrations/ (for schema tweaks)
    • app/Providers/AppServiceProvider.php (if extending functionality)

Implementation Patterns

Core Workflows

  1. Generating Short URLs:

    // Basic creation
    $shortUrl = ShortUrl::create('https://example.com');
    
    // With custom key (optional)
    $shortUrl = ShortUrl::create('https://example.com', 'MY-CUSTOM-KEY');
    
    // With tracking enabled (if configured)
    $shortUrl = ShortUrl::create('https://example.com', null, true);
    
  2. Redirecting to Original URL:

    // In a route (e.g., `Route::get('/{key}', ...)`)
    $shortUrl = ShortUrl::findByKey($key);
    return redirect()->to($shortUrl->long_url);
    
  3. Batch Processing:

    $urls = ['https://example.com/1', 'https://example.com/2'];
    $shortUrls = ShortUrl::createMultiple($urls);
    
  4. Tracking Visits:

    // Manually log a visit (e.g., in middleware)
    ShortUrl::logVisit($shortUrlId, $ipAddress, $userAgent);
    

Integration Tips

  1. Middleware for Tracking:

    // app/Http/Middleware/TrackShortUrl.php
    public function handle($request, Closure $next) {
        if (ShortUrl::isShortUrlRequest($request)) {
            ShortUrl::logVisit($key, $request->ip(), $request->userAgent());
        }
        return $next($request);
    }
    
  2. Customizing the Short URL Domain: Update config/short-url.php:

    'domain' => env('SHORT_URL_DOMAIN', 'short.yourdomain.com'),
    
  3. Extending the Model:

    // app/Models/ShortUrlExtension.php
    namespace App\Models;
    
    use AshAllenDesign\ShortUrl\Models\ShortUrl as BaseShortUrl;
    
    class ShortUrl extends BaseShortUrl {
        public function customMethod() {
            return $this->created_at->diffForHumans();
        }
    }
    

    Override the provider in AppServiceProvider:

    ShortUrl::setModel(\App\Models\ShortUrl::class);
    
  4. API Endpoints:

    // Create short URL via API
    Route::post('/short-url', function (Request $request) {
        $shortUrl = ShortUrl::create($request->long_url);
        return response()->json(['short_url' => $shortUrl->short]);
    });
    

Gotchas and Tips

Pitfalls

  1. Key Collisions:

    • The package uses a hash-based key generator by default. If you manually specify keys, ensure they are unique to avoid Illuminate\Database\QueryException.
    • Fix: Use ShortUrl::generateKey() to generate a unique key programmatically.
  2. Tracking Overhead:

    • Enabling tracking adds database writes on every visit. For high-traffic sites, consider:
      • Disabling tracking for anonymous users.
      • Using a queue (ShortUrl::logVisit($id, ...) supports queueing).
  3. Domain Configuration:

    • Forgetting to set SHORT_URL_DOMAIN in .env will break short URL generation.
    • Fix: Ensure config/short-url.php reflects your environment:
      'domain' => env('SHORT_URL_DOMAIN', 'short.yourdomain.com'),
      
  4. Migration Conflicts:

    • If you modify the short_urls table schema, run php artisan migrate:fresh to avoid conflicts.
    • Tip: Use php artisan migrate:status to check for pending migrations.

Debugging

  1. Log Short URL Creation: Enable debug mode in config/short-url.php:

    'debug' => env('APP_DEBUG', false),
    

    Logs will appear in storage/logs/laravel.log.

  2. Verify Key Generation: Check if keys are being generated correctly:

    $key = ShortUrl::generateKey('https://example.com');
    dd($key); // Should output a consistent hash (e.g., "abc123")
    
  3. Test Redirects Locally: Use php artisan serve and test redirects with:

    curl -v http://localhost:8000/YOUR_KEY
    

Extension Points

  1. Custom Key Generators: Bind a custom key generator in AppServiceProvider:

    ShortUrl::extend(function ($app) {
        $app->singleton('short-url.key-generator', function () {
            return new \App\Services\CustomKeyGenerator();
        });
    });
    
  2. Event Listeners: Listen for ShortUrlCreated events:

    // app/Listeners/LogShortUrlCreation.php
    public function handle(ShortUrlCreated $event) {
        \Log::info("Short URL created: {$event->shortUrl->short}");
    }
    

    Register in EventServiceProvider:

    protected $listen = [
        'AshAllenDesign\ShortUrl\Events\ShortUrlCreated' => [
            'App\Listeners\LogShortUrlCreation',
        ],
    ];
    
  3. Custom Storage: Override the default Eloquent model to use a different storage backend (e.g., Redis):

    // app/Models/ShortUrl.php
    use Illuminate\Database\Eloquent\Model as Eloquent;
    use AshAllenDesign\ShortUrl\Contracts\ShortUrlContract;
    
    class ShortUrl extends Eloquent implements ShortUrlContract {
        use \AshAllenDesign\ShortUrl\Traits\ShortUrlTrait;
    
        protected $connection = 'redis';
        protected $table = 'short_urls_cache';
    }
    

Performance Tips

  1. Cache Short URLs: Cache the ShortUrl model in AppServiceProvider:

    ShortUrl::setCacheDuration(60); // Cache for 60 minutes
    
  2. Batch Inserts: Use createMultiple() for bulk operations to reduce database load:

    $urls = collect(range(1, 100))->map(fn($i) => "https://example.com/$i");
    ShortUrl::createMultiple($urls->toArray());
    
  3. Disable Tracking for Bots: Skip tracking for known bots in middleware:

    if (str_contains($request->userAgent(), 'Bot')) {
        return $next($request);
    }
    ShortUrl::logVisit($key, $request->ip(), $request->userAgent());
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
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