Search code examples
phpcodeignitercodeigniter-4

Not redirected to specific URL in Codeigniter 4


Why is it that whenever I redirect something through the constructor of my Codeigniter 4 controller is not working?

<?php namespace App\Controllers\Web\Auth;

class Register extends \App\Controllers\BaseController
{
    function __construct()
    {
        if(session('username')){
            return redirect()->to('/dashboard');
        }
    }
    public function index()
    {
        // return view('welcome_message');
    }
}

But if I put it inside index it's working as expected.

public function index()
{
        if(session('username')){
            return redirect()->to('/dashboard');
        }
}

The thing is, I do not want to use it directly inside index because I it need on the other method of the same file.


Solution

  • As per the Codeigniter forum, you can no longer use the redirect method in the constructor to redirect to any of the controllers.

    Please refer the below link for more information

    https://forum.codeigniter.com/thread-74537.html

    It clearly states that redirect() will return a class instance instead of setting a header and you cannot return an instance of another class while instantiating a different class in PHP.

    So that's why you can't use redirect method in constructor.

    Instead, what I can suggest to you is that use the header method and redirect to your desired controller.

    <?php namespace App\Controllers\Web\Auth;
    
    class Register extends \App\Controllers\BaseController
    {
        function __construct()
        {
            if(session('username')){
                header('Location: /dashboard');
            }
        }
    }
    

    If that's not feasible or difficult to achieve you can follow the below code

    <?php namespace App\Controllers\Web\Auth;
    
    class Register extends \App\Controllers\BaseController
    {
        function __construct()
        {
            //call to session exists method
            $this->is_session_available();
        }
    
        private function is_session_available(){
            if(session('username')){
                return redirect()->to('/dashboard');
            }else{
                return redirect()->to('/login');
            }
        }
    }
    

    The 2nd solution will be more interactive than the first one. And make sure the method is private. So that it should not be called from other class instances.

    The community team has also given a solution to look into the controller filter.

    https://codeigniter4.github.io/CodeIgniter4/incoming/filters.html

    Please refer to the thread. I hope it may help you in finding a better solution.