How to Redirect in Laravel: Simple Guide with Examples
In Laravel, you can redirect users using the
redirect() helper function. It allows you to send users to a different URL, route, or back to the previous page easily by chaining methods like to(), route(), or back().Syntax
The redirect() helper is used to create a redirect response. You can use it in several ways:
redirect()->to('url'): Redirects to a specific URL.redirect()->route('route.name'): Redirects to a named route.redirect()->back(): Redirects back to the previous page.
Each method returns a response that tells the browser to load a new page.
php
return redirect()->to('https://example.com'); return redirect()->route('home'); return redirect()->back();
Example
This example shows a controller method that redirects a user to the home route after a successful action.
php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class ExampleController extends Controller { public function store(Request $request) { // Imagine saving data here // Redirect to named route 'home' return redirect()->route('home')->with('status', 'Data saved successfully!'); } }
Output
Redirects user to the URL defined by the 'home' route with a flash message 'Data saved successfully!'
Common Pitfalls
Common mistakes when redirecting in Laravel include:
- Forgetting to return the redirect response, which means the redirect won't happen.
- Using
redirect('url')instead ofredirect()->to('url')which still works but is less explicit. - Not defining the named route used in
redirect()->route('name'), causing errors.
php
<?php // Wrong: missing return, redirect won't work redirect()->route('home'); // Right: return the redirect response return redirect()->route('home');
Quick Reference
| Method | Description | Example |
|---|---|---|
| redirect()->to('url') | Redirects to a specific URL | return redirect()->to('https://example.com'); |
| redirect()->route('name') | Redirects to a named route | return redirect()->route('home'); |
| redirect()->back() | Redirects back to previous page | return redirect()->back(); |
| with('key', 'value') | Adds flash data to the session | return redirect()->route('home')->with('status', 'Success'); |
Key Takeaways
Always return the redirect response to make the redirect work.
Use redirect()->route('name') to redirect to named routes safely.
Use redirect()->back() to send users back to the previous page.
You can add flash messages with with('key', 'value') when redirecting.
Check that named routes exist to avoid errors during redirects.