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

Filament Short Url Laravel Package

a21ns1g4ts/filament-short-url

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require a21ns1g4ts/filament-short-url
    php artisan vendor:publish --provider="AshAllenDesign\ShortURL\Providers\ShortURLProvider"
    php artisan migrate
    
    • Verify the short_urls table exists in your database.
  2. Register Plugin: Add to your Filament panel provider:

    Filament::registerPanel(
        Panel::make()
            ->plugins([
                \A21ns1g4ts\FilamentShortUrl\FilamentShortUrlPlugin::make(),
            ]),
    );
    
  3. First Use Case:

    • Access the Short URLs resource in Filament (/admin/resources/short-urls).
    • Create a short URL by entering a long URL (e.g., https://example.com/long-path) and a slug (e.g., my-short-slug).
    • The system auto-generates a short URL like yourdomain.com/my-short-slug.

Implementation Patterns

Core Workflows

  1. Generating Short URLs:

    • Use the ShortUrl model directly:
      use AshAllenDesign\ShortURL\Models\ShortUrl;
      
      $shortUrl = ShortUrl::create([
          'long_url' => 'https://example.com/long-path',
          'slug' => 'custom-slug', // Optional; auto-generated if omitted
      ]);
      
    • Retrieve the short URL via:
      $shortUrl->shortUrl; // e.g., "yourdomain.com/custom-slug"
      
  2. Redirect Logic:

    • Add a route to handle redirects (e.g., in routes/web.php):
      Route::get('/{slug}', [\AshAllenDesign\ShortURL\Http\Controllers\ShortUrlController::class, 'redirect'])
          ->where('slug', '[\w\-]+');
      
    • The controller automatically resolves the slug to the original URL.
  3. Bulk Operations:

    • Use Filament’s Actions (e.g., "Generate Short URLs") to batch-create entries from a CSV or database query.
  4. Customizing Slugs:

    • Override slug generation in a service provider:
      ShortUrl::creating(function ($model) {
          $model->slug = Str::slug($model->long_url, '-');
      });
      
  5. Integration with Filament Forms:

    • Add a short URL field to a Filament resource:
      use A21ns1g4ts\FilamentShortUrl\Forms\Components\ShortUrl;
      
      ShortUrl::make('short_url')
          ->required()
          ->rules(['required', 'url'])
      

Advanced Patterns

  1. Custom Short Domains:

    • Extend the ShortUrl model to support multiple domains:
      $shortUrl = ShortUrl::create([
          'long_url' => 'https://example.com',
          'slug' => 'custom-slug',
          'domain' => 'short.yourdomain.com', // Custom domain
      ]);
      
    • Update the redirect route to handle subdomains:
      Route::get('{domain}/{slug}', [ShortUrlController::class, 'redirect'])
          ->where(['domain' => 'short\.yourdomain\.com', 'slug' => '[\w\-]+']);
      
  2. Analytics Tracking:

    • Hook into the redirect event to log clicks:
      ShortUrl::observe(\AshAllenDesign\ShortURL\Observers\ShortUrlObserver::class);
      
    • Extend the observer to add custom logic (e.g., increment a clicks counter).
  3. API Endpoints:

    • Expose short URL creation via API:
      Route::post('/api/short-urls', function (Request $request) {
          return ShortUrl::create($request->validate([
              'long_url' => 'required|url',
              'slug' => 'nullable|string',
          ]));
      });
      
  4. Filament Widgets:

    • Display recent short URLs in a dashboard widget:
      use A21ns1g4ts\FilamentShortUrl\Widgets\ShortUrlStats;
      
      ShortUrlStats::class,
      

Gotchas and Tips

Common Pitfalls

  1. Slug Conflicts:

    • If a slug already exists, the package auto-increments a suffix (e.g., -1). To customize:
      ShortUrl::creating(function ($model) {
          $model->slug = $model->slug . '-' . Str::random(4);
      });
      
  2. Route Caching:

    • After adding the redirect route, clear route cache:
      php artisan route:clear
      
  3. Database Indexes:

    • Ensure the slug column has a unique index (handled by the migration, but verify if extending the model).
  4. HTTPS Redirects:

    • If using HTTPS, ensure the redirect route enforces SSL:
      Route::get('/{slug}', [ShortUrlController::class, 'redirect'])
          ->where('slug', '[\w\-]+')
          ->middleware('web');
      
  5. Filament Permissions:

    • Restrict access to the Short URLs resource via Filament’s Policy system:
      ShortUrl::resource()->visibleTo(fn (User $user) => $user->can('manage-short-urls'));
      

Debugging Tips

  1. Missing Redirects:

    • Check if the route is registered:
      php artisan route:list | grep short-url
      
    • Verify the slug column in the database matches the URL pattern.
  2. Auto-Generated Slugs:

    • Override the slug generation logic if defaults don’t fit your use case (e.g., for non-English URLs):
      ShortUrl::creating(function ($model) {
          $model->slug = Str::of($model->long_url)->afterLast('/')->slug('-');
      });
      
  3. Performance:

    • Add an index to long_url if querying by it frequently:
      Schema::table('short_urls', function (Blueprint $table) {
          $table->index('long_url');
      });
      
  4. Testing:

    • Use Filament’s testing tools to test the plugin:
      $this->actingAs($user)
           ->get('/admin/resources/short-urls')
           ->assertStatus(200);
      

Extension Points

  1. Custom Storage:

    • Extend the ShortUrl model to store additional metadata (e.g., expires_at, tags):
      Schema::table('short_urls', function (Blueprint $table) {
          $table->timestamp('expires_at')->nullable();
          $table->string('tags')->nullable();
      });
      
  2. Webhook Events:

    • Dispatch events for short URL creation/redirection:
      ShortUrl::created(function ($shortUrl) {
          event(new ShortUrlCreated($shortUrl));
      });
      
  3. Custom Validation:

    • Add rules to the ShortUrl model:
      protected static function booted()
      {
          static::validate(function (NewShortUrl $validation) {
              $validation->rule(function ($attribute, $value, $fail) {
                  if (str_contains($value, 'blocked-domain.com')) {
                      $fail('Domain not allowed.');
                  }
              });
          });
      }
      
  4. Localization:

    • Translate slugs or messages (e.g., for Filament forms):
      'labels' => [
          'title' => __('Short URL'),
          'slug' => __('Custom Slug'),
      ],
      
  5. Rate Limiting:

    • Protect the redirect endpoint from abuse:
      Route::get('/{slug}', [ShortUrlController::class, 'redirect'])
          ->middleware(['throttle:100,1']);
      
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
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