Welcome Guest, Not a member yet? Register   Sign In
Redirect in initController
#1

I want to redirect to another controller from initController based on some conditions but ci4 is not redirecting and directly accessing the index method.

can anyone help me with that why ci4 not redirecting while in ci3 we can redirect from constructor.

for example : 

public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) {
        parent::initController($request, $response, $logger);
         if($this->data['menu_key']  == ''){
            return redirect()->to('Dashboard');
        }
}
Reply
#2

initController is called in __construct()
But the constructor should not return anything - it only has property setting
Use filters or add a redirect to each method
Simple CI 4 project for beginners codeigniter-expenses
Reply
#3

CI3's redirect() works everywhere because it is implemented in a forced way, setting headers and exiting PHP.

However, such a forced implementation is not recommended in modern times. It is not possible to write test code for it, and it is not usable in Long-living PHP (like Swoole) at all.

CI4's redirect() has been redesigned to return a Response object; it will not work in a constructor because it cannot return a Response object.

If you really want to redirect within the constructor, you can do so by throwing a RedirectException.
https://codeigniter4.github.io/CodeIgnit...texception
However, throwing an exception implies that it is an exceptional process that would not normally occur, so it is not recommended for normal processes.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB