Tom
Tom

Reputation: 79

(CI 4) How to redirect within Controller?

how can I refer to another within one controller? In CI3 (for example in the controller client.php) I solved this as follows:

redirect('/Clients', 'refresh');

but that no longer seems to work in CI4. (Msg: "route cannot be found while reverse-routing.") I Also tried

redirect()->route('/Clients');

but the error is the same.

redirect()->to('/Clients');

redirects nowhere (no output, nothing)

For a better understanding: I want to use a controller (e.g. Clients/create to Clients/details)

Upvotes: 0

Views: 3425

Answers (2)

objecttothis
objecttothis

Reputation: 45

@ViLar gives the correct answer, but it's important to note that when using auto routing the CI3 version redirect('home'); becomes return redirect()->to('home');

It's confusing to just say "Going to a specific URI" and omit that this means auto routed controllers.

Upvotes: 0

ViLar
ViLar

Reputation: 1094

What you should notice is that redirect() does not just set headers like it used to do in CI3. In CI4 it returns a RedirectResponse object with which you can ask your controller to do a redirection.
To do so, you need to return this RedirectResponse object inside your controller. Without the return statement, the redirection won't happen.

An other thing to notice is that redirect() can be called with some "options" :

Going to a named route

return redirect()->route('named_route'); 

or

 return redirect('named_route');

To use this, you need to add a named routes in your app/Config/Routes.php file :

$routes->get('/', 'MyController::index', ['as' => 'named_route']);

Going to a specific URI

return redirect()->to('Clients');

It will redirect you to your base url with /Clients at the end.

Please check out the doc for further informations : https://codeigniter.com/user_guide/general/common_functions.html#redirect

Upvotes: 3

Related Questions