0

I'm using CodeIgniter 4.

I have 2 controllers:

<?php namespace App\Controllers;

class Dashboard extends BaseController{

    public function index(){
        
        //pre-condition - logged
        if(!$this->session->has("email")){

            //go to login
            return redirect()->route("login");

        }

        return view("dashboard");

    }

}

//---------------------

class Profile extends BaseController{...}

In those 2 controllers I have some methods which represent routes /dashboard, /profile, /profile/settings, etc.

In every method I have the same pre-codition if(...){ return redirect()->route("login"); }.

This pre-condition check if user is logged.

How I can set this pre-condition to be at all methods from controller, without rewriting in every method from Dashboard and Profile?

KunLun
  • 3,109
  • 3
  • 18
  • 65
  • why not you put your condition on Construct function? – MD. Jubair Mizan Jul 26 '20 at 09:31
  • @MD.JubairMizan I don't know how. I'm relative new with CodeIgniter and PHP. – KunLun Jul 26 '20 at 09:33
  • I am writting a answer try this after call your class it should work – MD. Jubair Mizan Jul 26 '20 at 09:35
  • 1
    A better practice is to use Controller Filters. You should take a look at this answer : https://stackoverflow.com/questions/63048335/codeigniter-redirect-to-doesnt-work-in-construct/63049135#63049135 and the doc : https://codeigniter4.github.io/userguide/incoming/filters.html. They answer, by design, your question – ViLar Jul 27 '20 at 08:23
  • @ViLar Really thank you. It is better/elegant than what I have done. – KunLun Jul 27 '20 at 10:34

2 Answers2

2
function __construct()
{
    parent::__construct();
    if ( ! $this->session->userdata('logged_in'))
    { 
        redirect('login');
    }
}
MD. Jubair Mizan
  • 1,539
  • 1
  • 12
  • 20
-1

You can run code in every method of a Controller by running it in the __construct() method:-

class Auth_Controller extends CI_Controller {
    function __construct()
    {
         parent::__construct();
    if ( ! $this->session->userdata('logged_in'))
    { 
        redirect('login');
    }
    }
}
KUMAR
  • 1,993
  • 2
  • 9
  • 26