Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Useful macros to make Laravel routes compact

Macros in Laravel are a great way to extend the framework’s functionality. And if you are a Laravel developer, you must have used them at some point.

I recently came across this tip on Twitter where you can use macros to make your Laravel routes compact. And I thought it was a great tip and worth sharing.

The mapToRedirect macro

So, let’s say you want to define a bunch of redirect routes. The usual way to do it would be like so.

Route::redirect('/about', '/about-us');
Route::redirect('/contact', '/contact-us');
Route::redirect('/blog', 'https://blog.example.com');

But macros can make it more compact. Here’s how we can define a macro called mapToRedirect in RouteServiceProvider that takes an array of routes and their corresponding redirect URLs.

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 here’s how to use it.

use Illuminate\Support\Facades\Route;

Route::mapToRedirect([
    '/about' => '/about-us',
    '/contact' => '/contact-us',
    '/blog' => 'https://blog.example.com',
]);

Pretty neat, right?

The mapToController macro

Another useful macro is mapToController which takes an array of routes and their corresponding controller methods.

Route::macro('mapToController', function ($map, $controller) {
    foreach ($map as $method => $action) {
        Route::match(
            ['get', 'post', 'put', 'delete'], 
            $action, 
            $controller . '@' . $method
        );
    }
});

And here’s how to use it.

Route::mapToController([
    'index' => '/',
    'show' => '/{id}',
    'create' => '/create',
    'store' => '/',
    'edit' => '/{id}/edit',
    'update' => '/{id}',
    'destroy' => '/{id}',
], 'App\Http\Controllers\ExampleController');

Conclusion

So, these are some useful macros that you can use to make your Laravel routes compact. I hope you found this tip useful. And if you have any other useful macros, feel free to share them in the comments below.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?