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
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"
Key Files to Review:
config/short-url.php (for customization)database/migrations/ (for schema tweaks)app/Providers/AppServiceProvider.php (if extending functionality)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);
Redirecting to Original URL:
// In a route (e.g., `Route::get('/{key}', ...)`)
$shortUrl = ShortUrl::findByKey($key);
return redirect()->to($shortUrl->long_url);
Batch Processing:
$urls = ['https://example.com/1', 'https://example.com/2'];
$shortUrls = ShortUrl::createMultiple($urls);
Tracking Visits:
// Manually log a visit (e.g., in middleware)
ShortUrl::logVisit($shortUrlId, $ipAddress, $userAgent);
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);
}
Customizing the Short URL Domain:
Update config/short-url.php:
'domain' => env('SHORT_URL_DOMAIN', 'short.yourdomain.com'),
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);
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]);
});
Key Collisions:
Illuminate\Database\QueryException.ShortUrl::generateKey() to generate a unique key programmatically.Tracking Overhead:
ShortUrl::logVisit($id, ...) supports queueing).Domain Configuration:
SHORT_URL_DOMAIN in .env will break short URL generation.config/short-url.php reflects your environment:
'domain' => env('SHORT_URL_DOMAIN', 'short.yourdomain.com'),
Migration Conflicts:
short_urls table schema, run php artisan migrate:fresh to avoid conflicts.php artisan migrate:status to check for pending migrations.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.
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")
Test Redirects Locally:
Use php artisan serve and test redirects with:
curl -v http://localhost:8000/YOUR_KEY
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();
});
});
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',
],
];
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';
}
Cache Short URLs:
Cache the ShortUrl model in AppServiceProvider:
ShortUrl::setCacheDuration(60); // Cache for 60 minutes
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());
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());
How can I help you explore Laravel packages today?