Redirection in a helper |
Hello there,
With ci3, I usually created a helper with a function called "redirect_if_not_logged_in()" that I called at the top of some controllers. The goal of that function was quite self-explanatory: it checked if the visitor was logged in and if not, redirected them to the login page. Alas, when trying to do the same with ci4, things get a bit complicated. The "redirect()" function I used to use doesn't actually redirect, but returns an elusive RedirectResponse (completely missing from the doc, by the way). The only thing I imagine myself doing for now is this: PHP Code: // in a helper: But sincerely, that's pretty much as much code to call the helper and use it than to simple copy-paste the code inside the controller. How can I redirect FROM the helper? Nice day to you all!
Hello,
I think the error is simply about the redirect() call. It has changed - try: PHP Code: return redirect()->to('user/login'); Code Igniter 4 is a change of paradigm. From my point of view, you should not work this way. I would rather: - create a method in my custom controller to check if a user is logged in or not, - call this method in the initController() method which is called by the framework. The code would be: PHP Code: <?php All (sub-)Controllers inheriting from BaseController would then require to be logged in. You can also use redirectIfNotLoggedIn() case-by-case to limit the audience in the same Controller (one view requires login, another does'nt). Regards,
OK, so I'm not calling a helper, I'm calling $this->redirectIfNotLoggedIn() inherited from the BaseController.
Here is my new code: PHP Code: // in BaseController: But that doesn't work! The response is correctly modified, but the page still displays without the redirection. Any other idea on what I should do to redirect? Site note: https://codeigniter4.github.io/userguide...l#redirect states that redirect() takes a string parameter called URI. This might be an error in the doc.
Your best solution is to use Controller Filters to do a logged in check and redirect if needed.
YES!!! A thousand times yes! This est exactly and precisely what I needed. Thanks a lot.
|
Welcome Guest, Not a member yet? Register Sign In |