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

给你一囗甜甜゛ 提交于 2020-11-25 03:45:10

问题


I have code in my controller

public function __construct()
{
   return redirect()->to('/auth');
   $this->validation =
     \Config\Services::validation();
   $this->title = 'Header Menu';
   $this->controller = 'user';
}

public function index()
{
  $data = [
     'title_prefix' => 'Profil',
     'title' => $this->title,
     'controller' => $this->controller,
     'button_add' => false,
     'validation' => $this->validation
    ];

  return view('user/index', $data);
}

it still show view('user/index'). How to get to return redirect()->to('/auth') in __construct() ? sorry i'm not speaking english well


回答1:


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



来源:https://stackoverflow.com/questions/63048335/codeigniter-redirect-to-doesnt-work-in-construct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!