PHP code example of rayzenai / url-manager

1. Go to this page and download the library: Download rayzenai/url-manager library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rayzenai / url-manager example snippets


'driver' => Stevebauman\Location\Drivers\MaxMind::class,

'maxmind' => [
    'local' => [
        'type' => 'city', // or 'country' for smaller file
        'path' => database_path('maxmind/GeoLite2-City.mmdb'),
    ],
],

use RayzenAI\UrlManager\UrlManagerPlugin;

public function panel(Panel $panel): Panel
{
    return $panel
        // ... other configuration
        ->plugin(UrlManagerPlugin::make());
}



namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use RayzenAI\UrlManager\Traits\HasUrl;

class Product extends Model
{
    use HasUrl;

    protected $fillable = [
        'name',
        'slug',
        'description',
        'is_active', // Or 'active' - configurable via activeUrlField() method
        // ... other fields
    ];

    /**
     * Define the URL path for this model
     * Required by HasUrl trait
     */
    public function webUrlPath(): string
    {
        return 'products/' . $this->slug;
    }

    /**
     * Define the active field name (optional)
     * Override this if your model uses 'active' instead of 'is_active'
     */
    public function activeUrlField(): string
    {
        return 'active'; // Default is 'is_active'
    }

    /**
     * Enable automatic view count tracking
     * Optional - implement this to track views on your model
     */
    public function getViewCountColumn(): ?string
    {
        return 'view_count'; // Return null if no view counting needed
    }

    /**
     * Define Open Graph tags for SEO
     * Optional but recommended
     */
    public function ogTags(): array
    {
        return [
            'title' => $this->name,
            'description' => $this->description,
            'image' => $this->image_url,
            'type' => 'product',
        ];
    }

    /**
     * Define sitemap change frequency
     * Optional - defaults to 'weekly'
     */
    public function getSitemapChangefreq(): string
    {
        return 'daily';
    }
}

use RayzenAI\UrlManager\Http\Middleware\HandleUrlRedirects;

return Application::configure(basePath: dirname(__DIR__))
    ->withMiddleware(function (Middleware $middleware): void {
        // Add redirect handler EARLY, before route model binding
        // This is critical so old URLs redirect before hitting 404
        $middleware->web(prepend: [
            HandleUrlRedirects::class,
        ]);

        // ... rest of your middleware configuration
    })
    // ... rest of configuration

use RayzenAI\UrlManager\Facades\UrlManager;

// Generate URL for a model
$product = Product::find(1);
UrlManager::generateUrl($product);

// Track a visit manually
UrlManager::trackVisit($product, auth()->id());

// Create a redirect
UrlManager::createRedirect('old-url', 'new-url', 301);

// Find URL by slug
$url = UrlManager::findBySlug('products/my-product');

// Get visit count
$visits = UrlManager::getVisitCount($product);

// Delete URL
UrlManager::deleteUrl($product);

use RayzenAI\UrlManager\Models\Url;

// Create a permanent redirect
Url::createRedirect('old-page', 'new-page', 301);

// Create a temporary redirect
Url::createRedirect('summer-sale', 'products/sale', 302);

'sitemap' => [
    'custom_routes' => [
        [
            'path' => '/about',
            'priority' => 0.7,
            'changefreq' => 'monthly',
            'lastmod' => null, // Optional: Carbon instance or date string
        ],
        [
            'path' => '/contact',
            'priority' => 0.6,
            'changefreq' => 'yearly',
        ],
        [
            'path' => '/blog',
            'priority' => 0.8,
            'changefreq' => 'daily',
            'lastmod' => now(), // Can use Carbon instance
        ],
    ],
],

   use RayzenAI\UrlManager\Services\GoogleSearchConsoleService;
   
   // Submit to Google only
   $result = GoogleSearchConsoleService::submitGoogleSitemap();
   
   // Submit to all search engines (Google + Bing note)
   $result = GoogleSearchConsoleService::submitToAllSearchEngines();
   

// Get the full URL for a model
$product = Product::find(1);
echo $product->webUrl(); // https://yoursite.com/products/my-product

// Get the admin URL
echo $product->adminUrl(); // /admin/products/1/edit

// Check if a model's URL is active
if ($product->url && $product->url->status === 'active') {
    // URL is active
}

class Product extends Model
{
    use HasUrl;

    protected $fillable = [
        'name',
        'slug',
        'view_count', // Add your view count column
        // ...
    ];

    /**
     * Enable automatic view count tracking
     * When visitors access this model's URL, the view_count column will be incremented
     */
    public function getViewCountColumn(): ?string
    {
        return 'view_count'; // Return null if you don't want view counting
    }
}

Schema::create('products', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('slug')->unique();
    $table->unsignedBigInteger('view_count')->default(0); // Add this
    $table->boolean('is_active')->default(true);
    $table->timestamps();
});

->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'track-url-visits' => \RayzenAI\UrlManager\Http\Middleware\TrackUrlVisits::class,
    ]);
})

protected $middlewareAliases = [
    // ...
    'track-url-visits' => \RayzenAI\UrlManager\Http\Middleware\TrackUrlVisits::class,
];

// For Livewire components
Route::get('/property/{slug}', PropertyDetails::class)
    ->middleware('track-url-visits')
    ->name('property');

// For API routes
Route::middleware(['track-url-visits'])->group(function () {
    Route::get('/api/products/{slug}', [ProductController::class, 'show']);
    Route::get('/api/categories/{slug}', [CategoryController::class, 'show']);
});

// Works with any route type - controllers, closures, Livewire, Inertia, etc.
Route::middleware(['auth', 'track-url-visits'])->group(function () {
    Route::get('/dashboard', Dashboard::class);
    Route::get('/profile', [ProfileController::class, 'show']);
});

// Add at the END of your routes/web.php
Route::fallback([\RayzenAI\UrlManager\Http\Controllers\UrlController::class, 'handle']);

// URL-level visit tracking (always available)
$url = $product->url;
echo $url->visits; // Total visits on the URL record
echo $url->last_visited_at; // Last visit timestamp

// Model-level view tracking (if getViewCountColumn() is implemented)
echo $product->view_count; // Total views on the model itself

return [
    // Database table name
    'table_name' => 'urls',
    
    // URL types available in your application
    'types' => [
        'product' => 'Product',
        'category' => 'Category',
        'page' => 'Page',
        // Add your custom types
    ],
    
    // Maximum redirect chain depth (prevents infinite loops)
    'max_redirect_depth' => 5,
    
    // Visit tracking
    'track_visits' => true,
    'visit_queue' => 'low', // Queue for visit tracking jobs
    
    // Sitemap configuration
    'sitemap' => [
        'enabled' => true,
        'path' => public_path('sitemap.xml'),
        'max_urls_per_file' => 10000,
        'default_changefreq' => 'weekly',
        'default_priority' => 0.5,
        'priorities' => [
            'product' => 0.8,
            'category' => 0.9,
            'page' => 0.6,
        ],

        // Custom static routes to    ],
];

use RayzenAI\UrlManager\Facades\UrlManager;

// Generate or update URL for a model
$url = UrlManager::generateUrl($product);

// Manually track a visit (normally handled automatically)
UrlManager::trackVisit($product, auth()->id(), ['source' => 'mobile']);

// Create redirects programmatically
UrlManager::createRedirect('/old-path', '/new-path', 301);

// Find URLs by slug
$url = UrlManager::findBySlug('products/my-product');

// Get all redirects
$redirects = UrlManager::getRedirects();

// Get visit count for a model
$totalVisits = UrlManager::getVisitCount($product);

// Delete URL for a model
UrlManager::deleteUrl($product);

'types' => [
    'product' => 'Product',
    'article' => 'Article',
    'custom_type' => 'Custom Type',
],

public function getSeoMetadata(): array
{
    return [
        'title' => $this->seo_title ?? $this->name,
        'description' => $this->seo_description ?? $this->description,
        'keywords' => $this->seo_keywords,
        'og_image' => $this->featured_image,
        'og_type' => 'article',
        'twitter_card' => 'summary_large_image',
    ];
}

// In a service provider or event listener
Event::listen('url-manager.url.visited', function ($url, $model) {
    // Log visit, send analytics, etc.
    Log::info("URL visited: {$url->slug}");
});

'sitemap' => [
    'images' => [
        'enabled' => true,
        'max_images_per_file' => 5000,
        
        // Configure which size to use for sitemap images
        // Options: 'icon', 'thumb', 'medium', 'large', 'full', etc.
        // Set to null to use original images
        'image_size' => 'large', // Default: 720px height
    ],
],

'image_sizes' => [
    'icon' => 64,       // 64px height
    'thumb' => 240,     // 240px height  
    'medium' => 480,    // 480px height
    'large' => 720,     // 720px height (recommended for sitemaps)
    'full' => 1080,     // 1080px height
],

'seo' => [
    'enabled_models' => [
        'App\Models\Product',
        'App\Models\Category',
        'App\Models\Blog',
        // Models that should have SEO titles
    ],
    'excluded_models' => [
        'App\Models\User',
        'App\Models\Order',
        // Models that should NOT have SEO titles
    ],
],

use RayzenAI\UrlManager\Filament\Forms\Components\UrlInput;

UrlInput::make('slug')
    ->sourceField('name') // Auto-generate from name field
    ->forModel(Product::class) // For proper validation

UrlInput::make('slug')
    ->allowUpdatingSlug() // Enables editing on existing records

   public function activeUrlField(): string
   {
       return 'active'; // Your model's active field name
   }
   
bash
php artisan vendor:publish --tag=url-manager-config
bash
php artisan vendor:publish --provider="Stevebauman\Location\LocationServiceProvider"
bash
php artisan vendor:publish --tag=url-manager-migrations
php artisan migrate
bash
# Check all models using HasUrl trait
php artisan url-manager:check

# Check a specific model
php artisan url-manager:check "App\Models\Product"
bash
php artisan urls:generate
bash
php artisan urls:generate "App\Models\Product"
bash
# Increase PHP memory limit and execution time
php -d memory_limit=2G -d max_execution_time=0 artisan urls:generate

# Or generate for specific models one at a time
php artisan urls:generate "App\Models\Product"
php artisan urls:generate "App\Models\Category"
php artisan urls:generate "App\Models\Blog"
bash
php artisan sitemap:generate
bash
php artisan sitemap:generate
bash
   php artisan sitemap:submit
   
bash
php artisan url-manager:populate-country-codes