CodeIgniter Forums
returning redirect from parent's function. - 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: returning redirect from parent's function. (/showthread.php?tid=76305)



returning redirect from parent's function. - s4if - 05-01-2020

Hi, I want to make simple authentication checking method in BaseController.php so it can be accessed by another controller like this:
PHP Code:
protected function mustLoggedIn()
{
    if (
is_null($this->session->get('logged_in'))) {
        
$this->session->setFlashdata(['error' => 'Maaf, anda harus login dulu']);
        return 
redirect()->to('/login');
        exit();
    }

then accessed like this:
PHP Code:
public function beranda()
{
    
$this->mustLoggedIn();
    return 
view('siswa/beranda');

but it didn't work in CI4. Is my method wrong?
How to implement login check like that in CI4?


RE: returning redirect from parent's function. - vincent78 - 05-02-2020

Hello,

The 'exit()' call after the 'return' will never be executed.

PHP Code:
protected function isLoggedIn()
{
    if (is_null($this->session->get('logged_in'))) {
        $this->session->setFlashdata(['error' => 'Maaf, anda harus login dulu']);
        return false;
    } else {
        return true;
    }


PHP Code:
public function beranda()
{
    if ($this->isLoggedIn()) {
        return view('siswa/beranda');
    } else {
        return redirect()->to('/login');
    }


Vincent


RE: returning redirect from parent's function. - kilishan - 05-03-2020

I think you might want to check out Controller Filters. They are designed to handle exactly that type of situation.