CodeIgniter Forums
Redirect from BaseController - 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: Redirect from BaseController (/showthread.php?tid=80532)



Redirect from BaseController - sevmusic - 11-12-2021

Hey gang, I am trying to redirect from my BaseController with a function called by the child Controller but it doesn't seem to work. Here is what I have.

BaseController.php

PHP Code:
class BaseController extends Controller
{
    /**
    * @var \CodeIgniter\Session\Session|mixed|null
    */
    protected $session;

    public function initController(RequestInterface $requestResponseInterface $responseLoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request$response$logger);
        $this->session = \Config\Services::session();
    }

    public function check_something()
    {
        // redirect if something in session doesn't check out
        if (empty($this->session->get('something'))) redirect()->to('/somewhere');
    }



ChildController.php

PHP Code:
class ChildController extends BaseController
{
    public function index(){
        // check something first
        $this->check_something();

        // if we are not redirected...
        echo 'everything checked out!';
    }



To answer the question: Yes, the session variable 'something' has not been created and empty($this->session->get('something')) returns true;

Any help greatly appreciated. Thank you!


RE: Redirect from BaseController - kilishan - 11-12-2021

You should look into controller filters for this type of a situation.


RE: Redirect from BaseController - sevmusic - 11-12-2021

(11-12-2021, 11:10 AM)kilishan Wrote: You should look into controller filters for this type of a situation.

BINGO!

Thanks!


RE: Redirect from BaseController - kenjis - 11-12-2021

redirect() is the most changed helper function.

3.x https://codeigniter.com/userguide3/helpers/url_helper.html#redirect
4.x https://codeigniter.com/user_guide/general/common_functions.html#redirect

In CI4, it returns RedirectResponse, and you must return it.