Codeigniter redirect()->to() doesnt work in __construct()

后端 未结 1 855
星月不相逢
星月不相逢 2020-12-21 18:27

I have code in my controller

public function __construct()
{
   return redirect()->to(\'/auth\');
   $this->validation =
     \\Config\\Services::valida         


        
相关标签:
1条回答
  • 2020-12-21 18:50

    It is an expected behavior that redirect() doesn't work inside a constructor.

    redirect() in CI4 doesn't just set headers but return a RedirectResponse object.
    Problem is : while being in the constructor of your controller, you can't return an instance of something else. You're trying to construct a Controller not a RedirectResponse.

    Good practice is to use Controller Filters

    Or you could add the redirect() inside your index function if there's only at this endpoint that you would like to redirect the user.

    Here's an example of the filter that would fit your need :
    Watch out your CI version. The parameter $arguments is needed since 4.0.4. Otherwise you have to remove it

    <?php
    
    namespace App\Filters;
    
    use CodeIgniter\HTTP\RequestInterface;
    use CodeIgniter\HTTP\ResponseInterface;
    use CodeIgniter\Filters\FilterInterface;
    
    class AuthFilter implements FilterInterface {
    
        public function before(RequestInterface $request, $arguments = null) {
            return redirect()->to('/auth');
        }
    
        //--------------------------------------------------------------------
    
        public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) {
        }
    
    }
    

    And in your app/Config/Filters edit those 2 variables in order to activate your filter :

    public $aliases = [
            'auth' => \CodeIgniter\Filters\AuthFilter::class,
        ];
    public $globals = [
            'before' => ['auth' => 'the_routes_you_want_to_redirect']
        ];
    

    You might want to check this thread aswell : https://forum.codeigniter.com/thread-74537.html

    0 讨论(0)
提交回复
热议问题