10-12-2019, 11:50 PM
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:
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!
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:
if (!function_exists('redirectIfNotLoggedIn'))
{
$session = \Config\Services::session();
if ($session->get('loggedUser') === null)
{
return redirect('user/login');
}
return null;
}
// in a controller:
public function create()
{
$redirection = redirectIfNotLoggedIn();
if ($redirection !== null)
{
return $redirection;
}
// ...
}
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!