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

c-delouvencourt/short-url

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

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

    use Cdelouvencourt\ShortUrl\Facades\ShortUrl;
    
    $shortUrl = ShortUrl::create('https://example.com/very-long-url');
    echo $shortUrl->short; // Outputs: e.g., "your-app.com/abc123"
    
  3. Where to Look First:

    • Check config/short-url.php for configuration options (e.g., custom domains, key length).
    • Review app/Models/ShortUrl.php (if published) to understand the Eloquent model structure.
    • Explore routes/web.php for default route bindings (e.g., /{shortKey}).

Implementation Patterns

Usage Patterns

  1. Generating Short URLs:

    • Basic Usage:
      $shortUrl = ShortUrl::create('https://example.com/long-url');
      
    • Custom Key:
      $shortUrl = ShortUrl::create('https://example.com/long-url', 'MYCUSTOMKEY');
      
    • Expiring URLs:
      $shortUrl = ShortUrl::create('https://example.com/long-url', null, now()->addDays(7));
      
  2. Retrieving Short URLs:

    • Fetch by short key:
      $shortUrl = ShortUrl::findByShortKey('abc123');
      
    • Redirect logic in routes:
      Route::get('/{shortKey}', function ($shortKey) {
          return redirect()->to(ShortUrl::findByShortKey($shortKey)->longUrl);
      });
      
  3. Tracking Visits:

    • Enable tracking in config/short-url.php:
      'track_visits' => true,
      
    • Manually log a visit:
      $shortUrl->logVisit(request()->ip());
      
  4. Bulk Operations:

    • Create multiple short URLs:
      $urls = ['url1', 'url2', 'url3'];
      $shortUrls = ShortUrl::createMultiple($urls);
      
  5. Custom Domains:

    • Configure in config/short-url.php:
      'domain' => 'short.yourdomain.com',
      
    • Use the facade to generate absolute URLs:
      $absoluteUrl = ShortUrl::getAbsoluteUrl($shortUrl);
      

Workflows

  1. API Integration:

    • Expose endpoints for generating short URLs:
      Route::post('/short-url', function (Request $request) {
          return ShortUrl::create($request->longUrl);
      });
      
    • Return JSON response:
      return response()->json(['short_url' => $shortUrl->short]);
      
  2. Queueing URL Creation:

    • Dispatch a job for async processing:
      use Cdelouvencourt\ShortUrl\Jobs\CreateShortUrl;
      
      CreateShortUrl::dispatch('https://example.com/long-url');
      
  3. Middleware for Tracking:

    • Create middleware to auto-log visits:
      namespace App\Http\Middleware;
      
      use Closure;
      use Cdelouvencourt\ShortUrl\Facades\ShortUrl;
      
      class TrackShortUrlVisits
      {
          public function handle($request, Closure $next)
          {
              if ($shortKey = $request->route('shortKey')) {
                  $shortUrl = ShortUrl::findByShortKey($shortKey);
                  $shortUrl->logVisit($request->ip());
              }
              return $next($request);
          }
      }
      
    • Register in app/Http/Kernel.php:
      protected $middleware = [
          // ...
          \App\Http\Middleware\TrackShortUrlVisits::class,
      ];
      
  4. Seeding Short URLs:

    • Use Laravel's seeder:
      use Cdelouvencourt\ShortUrl\Models\ShortUrl;
      use Illuminate\Database\Seeder;
      
      class ShortUrlSeeder extends Seeder
      {
          public function run()
          {
              ShortUrl::create(['long_url' => 'https://example.com']);
          }
      }
      

Integration Tips

  1. Customize the Model:

    • Extend the ShortUrl model to add custom fields:
      namespace App\Models;
      
      use Cdelouvencourt\ShortUrl\Models\ShortUrl as BaseShortUrl;
      
      class ShortUrl extends BaseShortUrl
      {
          protected $casts = [
              'custom_field' => 'string',
          ];
      }
      
    • Update the facade to use your custom model:
      // In AppServiceProvider's boot method
      ShortUrl::setModel(\App\Models\ShortUrl::class);
      
  2. Custom Key Generation:

    • Override the key generator:
      use Cdelouvencourt\ShortUrl\Contracts\ShortUrlGenerator;
      
      class CustomShortUrlGenerator implements ShortUrlGenerator
      {
          public function generate()
          {
              return Str::random(8); // Custom logic
          }
      }
      
    • Bind the generator in AppServiceProvider:
      $this->app->bind(ShortUrlGenerator::class, CustomShortUrlGenerator::class);
      
  3. Validation:

    • Validate long URLs before creation:
      use Illuminate\Support\Facades\Validator;
      
      $validator = Validator::make(['longUrl' => $request->longUrl], [
          'longUrl' => 'required|url|max:2048',
      ]);
      
  4. Caching:

    • Cache short URLs to reduce database load:
      $shortUrl = Cache::remember("short_url_{$longUrl}", now()->addHours(1), function () use ($longUrl) {
          return ShortUrl::create($longUrl);
      });
      

Gotchas and Tips

Pitfalls

  1. Key Collisions:

    • The package uses a random key generator by default, but collisions can occur with high volume.
    • Fix: Implement a retry mechanism or use a deterministic key generator for critical URLs.
      $shortUrl = ShortUrl::create('https://example.com', 'UNIQUE_KEY');
      
  2. Tracking Overhead:

    • Enabling visit tracking adds database writes on every redirect.
    • Fix: Use queueing for visit logs or disable tracking for non-critical URLs.
      'track_visits' => env('SHORT_URL_TRACK_VISITS', false),
      
  3. Custom Domain Misconfiguration:

    • Forgetting to configure the domain in config/short-url.php will break absolute URL generation.
    • Fix: Always set the domain, even if it's a subdomain of your main site.
      'domain' => env('SHORT_URL_DOMAIN', 'short.yourdomain.com'),
      
  4. Migration Conflicts:

    • If you modify the short_urls table manually, migrations may fail.
    • Fix: Publish and modify the migration file instead of altering the table directly.
      php artisan vendor:publish --provider="Cdelouvencourt\ShortUrl\ShortUrlServiceProvider" --tag="migrations"
      
  5. Rate Limiting:

    • High traffic can overwhelm the key generation or tracking systems.
    • Fix: Implement rate limiting in your routes or use a queue for visit tracking.
      Route::middleware(['throttle:60,1'])->get('/{shortKey}', function ($shortKey) {
          // Redirect logic
      });
      

Debugging

  1. Short URL Not Found:

    • Check if the short key exists in the database:
      $shortUrl = ShortUrl::where('short_key', $shortKey)->first();
      
    • Verify the route binding in routes/web.php:
      Route::get('/{shortKey}', [ShortUrlController::class, 'redirect'])->where('shortKey', '.*');
      
  2. Redirect Loop:

    • Ensure the short field in the database matches the route parameter.
    • Check for case sensitivity issues in the short key.
  3. Tracking Not Working:

    • Verify track_visits is enabled in the config.
    • Check if the middleware is registered in Kernel.php.
  4. Custom Model Not Loading:

    • Ensure the facade is bound to your custom model in AppServiceProvider:
      ShortUrl::setModel(\App\Models\ShortUrl::class);
      

Tips

  1. Environment-Specific Config:
    • Use environment variables for sensitive or environment-specific settings:
      'domain' => env('SHORT_URL
      
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui