Laravel Custom mapToRedirect Route Macro

We know In Laravel, a macro is a way to add new functionality or extend existing functionality to an existing class or object. Macros allow you to define your own methods on Laravel's core classes, such as collections, models, and requests.

In this snippet, we'll create a custom Route macro named mapToRedirect.

Suppose, we need to define a bunch of redirect routes. Usually, we do that in this way:

Route::redirect('/old-url', '/new-url');
Route::redirect('/about', '/about-us');
Route::redirect('/contact', '/contact-us');

But by using Macro, we can compactly do the same thing.

Let's create the Macro. Open app\Providers\RouteServiceProvider.php and write the macro like this:

RouteServiceProvider.php
namespace App\Providers;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Route::macro('mapToRedirect', function ($map, $status = 301) {
            foreach ($map as $from => $to) {
                Route::redirect($from, $to, $status);
            }
        });
    }
}

And this is how we can use it:

use Illuminate\Support\Facades\Route;

Route::mapToRedirect([
    '/old-url' => '/oldnewurl',
    '/about' => '/about-us',
    '/contact' => '/contact-us',
]);

Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.