Laravel Redirect Routes Without Controllers

laravel routes


Laravel Redirect Routes Without Controllers

In Laravel, you don’t always need a controller to handle route redirections. Laravel provides a simple and efficient way to redirect routes using built-in methods. This helps keep your routing clean and avoids unnecessary controller logic.

1. Using Route::redirect()

Laravel offers the Route::redirect() method to quickly redirect one route to another without defining a controller.

Example:

Route::redirect('/old-route', '/new-route');

By default, this redirects with a 302 status code (temporary redirect). If you need a permanent redirect (301), specify it like this:

Route::redirect('/old-route', '/new-route', 301);

2. Redirect with Query Parameters

You can also pass query parameters by appending them in the URL:

Route::redirect('/contact', '/support?source=contact');

3. Conditional Redirects Using Closures

Sometimes, you may need more control over redirection logic. Instead of defining a controller, you can use a closure:

Route::get('/dashboard', function () {
    return redirect('/home');
});

4. Using Route::permanentRedirect()

For SEO-friendly permanent redirects (301), Laravel provides Route::permanentRedirect():

Route::permanentRedirect('/blog', '/news');

This is equivalent to:

Route::redirect('/blog', '/news', 301);

5. Redirecting to External URLs

Need to redirect users to an external website?

Route::get('/google', function () {
    return redirect()->away('https://www.google.com');
});

Conclusion

Using Laravel's built-in redirect methods, you can easily handle route redirections without creating unnecessary controllers. This keeps your application lightweight and improves performance.

Happy coding! 🚀