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.
Like this article?
Buy me a coffee👋 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.