Laravel Routing Macro

Ever find yourself writing the following code a decent amount of times in your Laravel router?

Route::get('/admin', function() {
return redirect()->to('/admin/dashboard');
});

Instead of writing that each time you want to redirect your users to a sub page of a route, an easier solution is to define a macro in your app’s service provider boot method. Laravel’s facades supports a macro function which accepts a initial route as its first argument, and a destination as its second. When the macro is called it will execute a redirect.

use Illuminate\Support\Facades\Route;
Route::macro('redirect', function($from, $to) {
return Route::get($from, function() use ($to) {
return redirect($to);
});
});

So now in your router all you need to do is the following:


Route::macro('/admin', '/admin/dashboard');

This idea was originally created by David Hemphill.