Search code examples
codeigniteruser-roles

redirect to admin and user based on user role in code igniter


If the admin is logging in. I want him to go to admin/dashboard. otherwise to the users dashboard. The controller of login is follow. In the users table, I have a column of 'role' and the value are '1' and '2'. 1 stands for admin and 2 for user. and there is separate table for role.

Login User function

public function login(){
    $data['title'] = 'Login';

    //validating form
    $this->form_validation->set_rules('username', 'Username', 'required');

    $this->form_validation->set_rules('password', 'Password', 'required');

    if($this->form_validation->run() ===FALSE){
        $this->load->view('templates/header');
        $this->load->view('users/login', $data);
        $this->load->view('templates/footer');
    }else{
        //Get username
        $username = $this->input->post('username');

        //Get password in md5 
        $password= md5($this->input->post('password'));

        //Login User.... passing username and password
        $user_id = $this->user_model->login($username, $password);

        //checking userid
        if($user_id){
            //creating session if user_id is present
            $user_data=array(
                'user_id'=>$user_id,
                'username'=>$username,
                'logged_in' => true
            );

            $this->session->set_userdata($user_data);
            //set message               
            $this->session->set_flashdata('user_loggedin', 'Login successful');
            redirect('posts');                  
        }else{
            //creating session if user_id is not present
            $this->session->set_flashdata('login_failed', ' Invalid credentials');
            redirect('users/login');
        }
    }
}

Solution

  • while validating the user, you have to send an array as a response to login call.

    $user_info = $this->user_model->login($username, $password); // User Info should be an Array $user_info = array('user_id' => '123', 'role' => '1'); if exist and $user_info = array(); if not
    
    
    if(isset($user_info['user_id']) && !empty($user_info['user_id'])) {
    $user_data=array(
            'user_id'=>$user_info['user_id'],
            'username'=>$username,
            'logged_in' => true
        );
    
    $this->session->set_userdata($user_data);
    $this->session->set_flashdata('user_loggedin', 'Login successful');
    if($user_info['role'] == 1){
        redirect('admin/dashboard');
    } else {
        redirect('user/dashboard');
    }
    
    }
    

    Sure this will help you.