Welcome Guest, Not a member yet? Register   Sign In
Redirection in a helper
#2

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
namespace App\Controllers;

use 
CodeIgniter\Controller;

class 
BaseController extends Controller
{

    public function 
redirectIfNotLoggedIn() {

        
$session = \Config\Services::session();
        if (
$session->get('loggedUser') === null)
        {
            return 
redirect()->to('user/login');
        }

    }

    
/**
     * Constructor.
     */
    
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        
// Do Not Edit This Line
        
parent::initController($request$response$logger);

        
//--------------------------------------------------------------------
        // Preload any models, libraries, etc, here.
        //--------------------------------------------------------------------
        // E.g.:
        // $this->session = \Config\Services::session();

        
$this->redirectIfNotLoggedIn();
    }





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,
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
RE: Redirection in a helper - by ahmad_arief - 10-03-2020, 04:58 AM



Theme © iAndrew 2016 - Forum software by © MyBB