PHP code example of vormkracht10 / laravel-redirects

1. Go to this page and download the library: Download vormkracht10/laravel-redirects 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/ */

    

vormkracht10 / laravel-redirects example snippets


return [
    /*
     * Available HTTP status codes for redirection.
     * Uncomment additional codes as needed.
     */
    'status_codes' => [
        301 => 'Moved Permanently',      // Permanent redirect, cached by browsers
        302 => 'Found',                  // Temporary redirect, not cached
        307 => 'Temporary Redirect',     // Temporary, maintains HTTP method
        308 => 'Permanent Redirect',     // Permanent, maintains HTTP method
    ],

    /*
     * The model to use for managing redirects.
     * Override this to use your own custom model.
     */
    'model' => Backstage\Redirects\Laravel\Models\Redirect::class,

    /*
     * Default status code for new redirects.
     * Can be overridden via REDIRECT_DEFAULT_STATUS_CODE env variable.
     */
    'default_status_code' => env('REDIRECT_DEFAULT_STATUS_CODE', 301),

    /*
     * Case sensitivity for URL matching.
     *
     * false: /example and /Example are treated as the same
     * true:  /example and /Example are treated as different URLs
     */
    'case_sensitive' => env('REDIRECT_CASE_SENSITIVE', false),

    /*
     * Trailing slash sensitivity for URL matching.
     *
     * false: /example and /example/ are treated as the same
     * true:  /example and /example/ are treated as different URLs
     */
    'trailing_slash_sensitive' => env('REDIRECT_TRAILING_SLASH_SENSITIVE', false),

    /*
     * Add trailing slash to redirect destinations.
     * Useful for maintaining URL consistency and SEO.
     */
    'trailing_slash' => env('REDIRECT_WITH_TRAILING_SLASH', false),

    /*
     * Middleware stack for handling redirects.
     * Order matters - first match wins.
     *
     * - HttpRedirects: Matches URLs with protocol/www variations
     * - WildRedirects: Partial URL matching (contains)
     * - StrictRedirects: Exact URL matching
     */
    'middleware' => [
        Backstage\Redirects\Laravel\Http\Middleware\HttpRedirects::class,
        Backstage\Redirects\Laravel\Http\Middleware\WildRedirects::class,
        Backstage\Redirects\Laravel\Http\Middleware\StrictRedirects::class,
    ],
];

use Backstage\Redirects\Laravel\Models\Redirect;

Redirect::create([
    'source' => '/old-page',
    'destination' => '/new-page',
    'code' => 301,
]);

use Backstage\Redirects\Laravel\Models\Redirect;

// Permanent redirect (301)
Redirect::create([
    'source' => '/old-blog-post',
    'destination' => '/new-blog-post',
    'code' => 301,
]);

// Temporary redirect (302)
Redirect::create([
    'source' => '/maintenance',
    'destination' => '/under-construction',
    'code' => 302,
]);

// Wildcard redirect (matches any URL containing the source)
Redirect::create([
    'source' => '/blog/category/',
    'destination' => '/articles/',
    'code' => 301,
]);

Redirect::create([
    'source' => 'example.com/old-url',
    'destination' => 'example.com/new-url',
    'code' => 301,
]);

use Backstage\Redirects\Laravel\Events\UrlHasChanged;

// When a blog post URL changes
event(new UrlHasChanged(
    oldUrl: 'https://example.com/old-slug',
    newUrl: 'https://example.com/new-slug',
    code: 301
));

// Created automatically by the listener
Redirect::create([
    'source' => 'https://example.com/old-slug',
    'destination' => 'https://example.com/new-slug',
    'code' => 301,
]);

use Backstage\Redirects\Laravel\Events\UrlHasChanged;
use Illuminate\Database\Eloquent\Model;

class BlogPost extends Model
{
    protected static function booted()
    {
        static::updating(function ($post) {
            if ($post->isDirty('slug')) {
                $oldUrl = route('blog.show', $post->getOriginal('slug'));
                $newUrl = route('blog.show', $post->slug);

                event(new UrlHasChanged($oldUrl, $newUrl, 301));
            }
        });
    }
}

Redirect::create([
    'source' => '/old-page',
    'destination' => '/new-page',
    'code' => 301,
]);

Redirect::create([
    'source' => '/old-page',
    'destination' => '/new-page?foo=bar',
    'code' => 301,
]);

$redirect = Redirect::where('source', '/old-page')->first();
echo $redirect->hits; // Number of times this redirect was used

// Most used redirects
$popular = Redirect::orderBy('hits', 'desc')->take(10)->get();

// Recently created redirects
$recent = Redirect::latest()->take(10)->get();

// Unused redirects (candidates for removal)
$unused = Redirect::where('hits', 0)->get();

Redirect::create([
    'source' => 'example.com/page',
    'destination' => 'example.com/new-page',
    'code' => 301,
]);

Redirect::create([
    'source' => '/blog/',
    'destination' => '/articles/',
    'code' => 301,
]);

Redirect::create([
    'source' => 'example.com/exact-page',
    'destination' => 'example.com/new-exact-page',
    'code' => 301,
]);

'middleware' => [
    // 1. Try HTTP matching first (protocol/www normalized)
    Backstage\Redirects\Laravel\Http\Middleware\HttpRedirects::class,

    // 2. Then wildcard matching
    Backstage\Redirects\Laravel\Http\Middleware\WildRedirects::class,

    // 3. Finally exact matching
    Backstage\Redirects\Laravel\Http\Middleware\StrictRedirects::class,
],

'middleware' => [
    Backstage\Redirects\Laravel\Http\Middleware\StrictRedirects::class,
],

namespace App\Models;

use Backstage\Redirects\Laravel\Models\Redirect as BaseRedirect;

class Redirect extends BaseRedirect
{
    // Add custom scopes
    public function scopeActive($query)
    {
        return $query->where('active', true);
    }

    // Add relationships
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    // Override redirect logic
    public function redirect(Request $request): ?RedirectResponse
    {
        // Custom logic before redirect
        \Log::info("Redirecting from {$this->source} to {$this->destination}");

        return parent::redirect($request);
    }
}

'model' => App\Models\Redirect::class,

$redirects = [
    ['source' => '/old-1', 'destination' => '/new-1', 'code' => 301],
    ['source' => '/old-2', 'destination' => '/new-2', 'code' => 301],
    ['source' => '/old-3', 'destination' => '/new-3', 'code' => 301],
];

foreach ($redirects as $redirect) {
    Redirect::create($redirect);
}

use Illuminate\Support\Facades\Storage;
use League\Csv\Reader;

$csv = Reader::createFromPath(Storage::path('redirects.csv'));
$csv->setHeaderOffset(0);

foreach ($csv->getRecords() as $record) {
    Redirect::create([
        'source' => $record['source'],
        'destination' => $record['destination'],
        'code' => $record['code'] ?? 301,
    ]);
}

// Only redirect if destination exists
if (Route::has('new-route')) {
    Redirect::create([
        'source' => '/old-route',
        'destination' => route('new-route'),
        'code' => 301,
    ]);
}

// BAD: Creates a redirect chain
// /page-1 → /page-2 → /page-3
Redirect::create(['source' => '/page-1', 'destination' => '/page-2', 'code' => 301]);
Redirect::create(['source' => '/page-2', 'destination' => '/page-3', 'code' => 301]);

// GOOD: Direct redirect
Redirect::create(['source' => '/page-1', 'destination' => '/page-3', 'code' => 301]);

// Perform the redirect
public function redirect(Request $request): ?RedirectResponse

// Increment hits counter (called automatically)
public function increment('hits'): void

use Backstage\Redirects\Laravel\Events\UrlHasChanged;

event(new UrlHasChanged(
    oldUrl: 'https://example.com/old',
    newUrl: 'https://example.com/new',
    code: 301 // Optional, defaults to 301
));

use Backstage\Redirects\Laravel\Models\Redirect;

it('redirects old URL to new URL', function () {
    Redirect::create([
        'source' => '/old',
        'destination' => '/new',
        'code' => 301,
    ]);

    $response = $this->get('/old');

    $response->assertRedirect('/new');
    $response->assertStatus(301);
});

it('preserves query strings', function () {
    Redirect::create([
        'source' => '/old',
        'destination' => '/new',
        'code' => 301,
    ]);

    $response = $this->get('/old?foo=bar');

    $response->assertRedirect('/new?foo=bar');
});

it('increments hits counter', function () {
    $redirect = Redirect::create([
        'source' => '/old',
        'destination' => '/new',
        'code' => 301,
    ]);

    expect($redirect->hits)->toBe(0);

    $this->get('/old');

    expect($redirect->fresh()->hits)->toBe(1);
});
bash
php artisan vendor:publish --tag="laravel-redirects-migrations"
php artisan migrate
bash
php artisan vendor:publish --tag="laravel-redirects-config"
bash
php artisan tinker
bash
composer analyse