CodeIgniter Forums
Correct way to re-direct in controller back to "index" - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Correct way to re-direct in controller back to "index" (/showthread.php?tid=89298)



Correct way to re-direct in controller back to "index" - joho - 02-02-2024

What is the correct way to re-direct the user back to "index"?

In my routes, I'm using $routes->match() to match URIs according to CRUD, so for "delete", there's:
Code:
$routes->match( ['get', 'post'], 'delete/(:segment)', [MyController::class, 'delete'] );

And then in "delete", in the Controller, I check for a valid parameter. If I don't get a valid parameter, I want to issue a re-direct to "/".
I've tried returing the "index" view, which is not good since it'll keep the URI at domain.com/delete.

I've tried setting up an additional route, as a catch-all for "delete" like so:
Code:
$routes->match( ['get', 'post'], 'delete/', [MyController::class, 'index'] );

But that will yield the same result (which is expected).

I've tried using redirect()->route like so:
Code:
return( redirect()->route( '' ) );

But that'll re-direct the browser to "https://domain.com/index.php/", which is ugly :-)

So, what I'm using now is simply this:
Code:
return( $this->response->redirect( base_url() ));

Is that the correct way of doing it?


RE: Correct way to re-direct in controller back to "index" - kenjis - 02-02-2024

You should not delete something with GET requests. GET should be safe (does not change any resources).

See https://codeigniter.com/user_guide/outgoing/response.html#redirect-to-a-uri-path
and https://codeigniter.com/user_guide/installation/running.html#configure-for-your-site-uris


RE: Correct way to re-direct in controller back to "index" - joho - 02-04-2024

Well, I'm not actually deleting anything on GET. That will simply display a confirmation prompt, which will do a POST, which will delete.