Manage redirects using database rules. Rules are intended to be very similar to Laravel default routes, so syntax is pretty easy to comprehend.

Overview

Laravel DB redirector

Build Downloads Stable License

Manage HTTP redirections in Laravel using database

Manage redirects using database rules. Rules are intended to be very similar to Laravel default routes, so syntax is pretty easy to comprehend.


Compatibility

The package is compatible with Laravel versions 5.5, 5.6, 5.7 and 5.8 and PHP versions 7.1 and 7.2

Installation

Install the package via composer:

composer require vkovic/laravel-db-redirector

Database redirector middleware needs to be added to middleware array:

// File: app/Http/Kernel.php

// ...

protected $middleware = [
    // ...
    \Vkovic\LaravelDbRedirector\Http\Middleware\DbRedirectorMiddleware::class
];

Run migrations to create table which will store redirect rules:

php artisan migrate

Usage: Simple Examples

Creating a redirect is easy. You just have to add db record via provided RedirectRule model. Default status code for redirections will be 301 (Moved Permanently).

use Vkovic\LaravelDbRedirector\Models\RedirectRule;

// ...

RedirectRule::create([
    'origin' => '/one/two',
    'destination' => '/three'
]);

You can also specify another redirection status code:

RedirectRule::create([
    'origin' => '/one/two',
    'destination' => '/three',
    'status_code' => 307 // Temporary Redirect
]);

You may use route parameters just like in native Laravel routes, they'll be passed down the road - from origin to destination:

RedirectRule::create([
    'origin' => '/one/{param}',
    'destination' => '/two/{param}'
]);

// If we visit: "/one/foo" we will end up at "two/foo"

Optional parameters can also be used:

RedirectRule::create([
    'origin' => '/one/{param1?}/{param2?}',
    'destination' => '/four/{param1}/{param2}'
]);

// If we visit: "/one" we'll end up at "/four
// If we visit: "/one/two" we'll end up at "/four/two"
// If we visit: "/one/two/three" we'll end up at "/four/two/three"

Chained redirects will also work:

RedirectRule::create([
    'origin' => '/one',
    'destination' => '/two'
]);

RedirectRule::create([
    'origin' => '/two',
    'destination' => '/three'
]);

RedirectRule::create([
    'origin' => '/three',
    'destination' => '/four'
]);

// If we visit: "/one" we'll end up at "/four"

We also can delete the whole chain at once (3 previous redirect records in this example):

RedirectRule::deleteChainedRecursively('/four');

Sometimes it's possible that you'll have more than one redirection with the same destination. So it's smart to surround code with try catch block, because exception will be raised in this case:

RedirectRule::create(['origin' => '/one/two', 'destination' => '/three/four']);
RedirectRule::create(['origin' => '/three/four', 'destination' => '/five/six']);

// One more with same destination ("/five/six") as the previous one.
RedirectRule::create(['origin' => '/ten/eleven', 'destination' => '/five/six']);

try {
    RedirectRule::deleteChainedRecursively('five/six');
} catch (\Exception $e) {
    // ... handle exception
}

Usage: Advanced

What about order of rules execution when given url corresponds to multiple rules. Let's find out in this simple example:

RedirectRule::create(['origin' => '/one/{param}/three', 'destination' => '/four']);
RedirectRule::create(['origin' => '/{param}/two/three', 'destination' => '/five']);

// If we visit: "/one/two/three" it corresponds to both of rules above,
// so, where should we end up: "/four" or "/five" ?
// ...
// It does not have anything to do with rule order in our rules table!

To solve this problem, we need to agree on simple (and logical) rule prioritizing:

Priority 1: Rules without named parameters have top priority:

Priority 2: If rule origin have named parameters, those with less named parameters will have higher priority

Priority 3: If rule origin have same number of named parameters, those where named parameters are nearer the end of the rule string will have priority

So lets examine our previous case, we have:

  • "/one/{param}/three" => "/four"
  • "/{param}/two/three" => "/five"

In this case both rules have the same number of named params, but in the first rule "{param}" is nearer the end of the rule, so it will have priority and we'll end up at "/four".


Contributing

If you plan to modify this Laravel package you should run tests that comes with it. Easiest way to accomplish this would be with Docker, docker-compose and phpunit.

First, we need to initialize Docker containers:

docker-compose up -d

After that, we can run tests and watch the output:

docker-compose exec app vendor/bin/phpunit
You might also like...
Auto Route Generating (Auto-Discovery) Package for Laravel.

Laravel Auto Routes _ _____ _ /\ | | | __ \ | |

Checks if a laravel route is vlaid
Checks if a laravel route is vlaid

Laravel Route Checker Checks if your Laravel routes has valid controllers Installation The package should be installed as a dev dependency, as there i

Create custom WordPress routes and redirects, restrict access by roles and/or capabilities. Routes made simple
Create custom WordPress routes and redirects, restrict access by roles and/or capabilities. Routes made simple

Create custom WordPress routes and redirects, restrict access by roles and/or capabilities. Routes made simple

Display your Laravel routes in the console, but make it pretty. 😎
Display your Laravel routes in the console, but make it pretty. 😎

Pretty Routes for Laravel Display your Laravel routes in the console, but make it pretty. 😎 Installation You can install the package via composer: co

Pretty routes for Laravel
Pretty routes for Laravel

Pretty Routes for Laravel Visualise your routes in pretty format. Installation composer require garygreen/pretty-routes If your using autodiscovery in

A super simple, clean and pretty error handler that replace the default error handler of PHP. You need only include this file!

php-custom-error-handler A super simple, clean and pretty error handler that replace the default error handler of PHP. You need just include only this

Laravel package for manage your URL redirects in database or other sources to get better SEO results

Laravel 8 and 9 package to manage URL redirections inside your Laravel application using different data sources. It allows a better SEO support for your Laravel site.

Textpattern-default-theme - Textpattern CMS default theme.

Textpattern CMS default theme This project is the source for the default theme that ships as standard with Textpattern CMS. It is intended as a starti

A composer plugin, to install differenty types of composer packages in custom directories outside the default composer default installation path which is in the vendor folder.

composer-custom-directory-installer A composer plugin, to install differenty types of composer packages in custom directories outside the default comp

CodeIgniter4 Attribute Routes. You can set Routes in Controllers as PHP8 Attributes.

CodeIgniter4 Attribute Routes This package generates a Routes File from the Attribute Routes in your Controllers. You can set routes in your Controlle

A very slight PHP framework, very easy to use and integrate.

A very slight PHP framework, very easy to use and integrate.

Very easy to use a current limiting component, the code is very simple, based on the webman framework.

Very easy to use a current limiting component, the code is very simple, based on the webman framework.

Pretty, simple and easy gallery
Pretty, simple and easy gallery

Auto Generating Gallery This is build with the awesome php framework Laravel 4. See the demo Pretty, simple and easy gallery. Upload albumfolder via f

Generate pretty release changelogs using the commit log and Github API.

zenstruck/changelog Generate pretty release changelogs using the commit log and Github API. Changelog entries are in the following format: {short hash

A high-performance backend cache system. It is intended for use in speeding up dynamic web applications by alleviating database load.

A high-performance backend cache system. It is intended for use in speeding up dynamic web applications by alleviating database load. Well implemented, it can drops the database load to almost nothing, yielding faster page load times for users, better resource utilization. It is simple yet powerful.

An easy way to desensitize your routes in your Laravel application

The package provides an easy way to desensitize your routes in your Laravel application. In short, Desensitize makes your routes case-insensitive, so you can access any of your routes whether they are lowercase, uppercase, or both.

Magic admin PHP SDK makes it easy to leverage Decentralized ID tokens to protect routes and restricted resources for your application.

Magic Admin PHP SDK The Magic Admin PHP SDK provides convenient ways for developers to interact with Magic API endpoints and an array of utilities to

Pretty Good Privacy (PGP) is an encryption program that provides cryptographic privacy and authentication for data communication.

Pretty Good Privacy (PGP) is an encryption program that provides cryptographic privacy and authentication for data communication. PGP is used for signing, encrypting, and decrypting texts, e-mails, files, directories, and whole disk partitions and to increase the security of e-mail communications. Phil Zimmermann developed PGP in 1991.

Comments
  • 404 Redirects

    404 Redirects

    I've inserted a non-existent link to redirect rules, when i visit the link it redirects me to the 404 page directly.Is there a way to run db-redirector before laravel's exception handler?

    opened by egesarisac 5
  • Tests not passing on PHP 7.3

    Tests not passing on PHP 7.3

    It seems that middleware is not being registered correctly in TestCase so it does not perform redirections.

    Error from phpunit:

    1) Vkovic\LaravelDbRedirector\Test\Integration\RoutingViaDbRedirectorTest::test_simple_redirect
    Response status code [404] is not a redirect status code.
    Failed asserting that false is true.
    
    opened by vkovic 0
Owner
Vladimir Ković
Founder @movor
Vladimir Ković
Create your routes using attributes in your controllers

Create your routes using attributes in your controllers

Raihel 3 Jan 5, 2023
Generate routes documentation

Laravel Route Documentation Maybe we are wondering where these routes lead or what could be their purpose? This package decides to solve this solution

Ahmet Barut 6 Nov 16, 2022
:tada: Release 2.0 is released! Very fast HTTP router for PHP 7.1+ (incl. PHP8 with attributes) based on PSR-7 and PSR-15 with support for annotations and OpenApi (Swagger)

HTTP router for PHP 7.1+ (incl. PHP 8 with attributes) based on PSR-7 and PSR-15 with support for annotations and OpenApi (Swagger) Installation compo

Sunrise // PHP 151 Jan 5, 2023
PhpRouter is a powerful, lightweight, and very fast HTTP URL router for PHP projects.

PhpRouter PhpRouter is a powerful, lightweight, and very fast HTTP URL router for PHP projects. Some of the provided features: Route parameters Predef

Milad Rahimi 152 Dec 28, 2022
A lightweight and very basic PHP router.

Katya A lightweight PHP router Configuration Para servidor Apache, en el directorio del proyecto crea y edita un archivo .htaccess con lo siguiente: <

Luis Rodríguez 0 Apr 4, 2022
Flight routing is a simple, fast PHP router that is easy to get integrated with other routers.

The PHP HTTP Flight Router divineniiquaye/flight-routing is a HTTP router for PHP 7.1+ based on PSR-7 and PSR-15 with support for annotations, created

Divine Niiquaye Ibok 16 Nov 1, 2022
Simple, fast and yet powerful PHP router that is easy to get integrated and in any project.

Simple, fast and yet powerful PHP router that is easy to get integrated and in any project. Heavily inspired by the way Laravel handles routing, with both simplicity and expand-ability in mind.

Simon Sessingø 472 Jan 4, 2023
PHPRouter is an easy-to-use, fast, and flexible PHP router package with express-style routing.

PHP-Router is a modern, fast, and adaptable composer package that provides express-style routing in PHP without a framework.

Ayodeji O. 4 Oct 20, 2022
A Laravel package that introduces a clean object based alternative to Laravel route files.

Laravel Route Registrars This package introduces a clean object based way to define your routes in a Laravel application. A tutorial on the basic prem

Ollie Codes 22 Nov 25, 2022
PHP routing (like laravel) (not complete yet)

PHP Router (under construction) This repository contains routing classes that enables you to define your routes similar to laravel 8 routes. Features

Kareem M. Fouad 6 Jan 16, 2022