Redirect with a Flash Message
To pass data (like success or error messages) during a redirect, you can use session flashdata.
Example:
Set flashdata in the controller before redirecting:
1 2 | session()->setFlashdata('success', 'Operation completed successfully.'); return redirect()->to('/dashboard'); |
Retrieve flashdata in the redirected page:
1 2 3 | if (session()->getFlashdata('success')) { echo session()->getFlashdata('success'); } |
Redirect with POST
/GET
Data
To pass query parameters or data, append them to the redirect URL.
1 | return redirect()->to('/search')->withInput(['query' => 'CodeIgniter']); |
Retrieve input in the redirected controller:
1 | $query = $this->request->getVar('query'); |
Conditional Redirect
You can dynamically redirect users based on conditions.
1 2 3 4 5 | if ($user->isAdmin) { return redirect()->to('/admin/dashboard'); } else { return redirect()->to('/user/dashboard'); } |
Use redirect()
Helper Function
The redirect()
function is a global helper and can be used without $this
or BaseController
.
Example:
1 | return redirect()->to('/home'); |