• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Redirection in a helper

#1
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:

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!
Reply


Messages In This Thread
Redirection in a helper - by SteeveDroz - 10-12-2019, 11:50 PM
RE: Redirection in a helper - by Ekley - 10-13-2019, 03:13 AM
RE: Redirection in a helper - by SteeveDroz - 10-13-2019, 09:54 PM
RE: Redirection in a helper - by kilishan - 10-14-2019, 06:38 AM
RE: Redirection in a helper - by SteeveDroz - 10-14-2019, 10:28 PM

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.