Tag Archives: index

cakephp3 – fixing the index method for admin and normal user

23666Say for example you dont want normal users being able to see a list of items in this example lets say its questions.  But at the same time you want an “admin” user to be able to see them.

The following function might help;

 public function index(){
        
		$user_id=$this->Auth->user('id');
		$role=$this->Auth->user('role');
		
		//check users role and show all questions if admin or just their questions of normal user
		
		if($role=='admin'){
			//show all questions
			$this->paginate = [
				'limit' =>20,
				'order' => ['Questions.modified' => 'desc'],
				'contain' => ['Users', 'Questionscategories']
			];
		}
		elseif($role=='user'){
			//show only the users stuff
			//set the pagnate options
			$this->paginate = [
				'limit' =>10,
				'order' => ['Questions.modified' => 'desc'],
				'contain' => ['Users', 'Questionscategories'],
				'conditions'=>['questions.user_id'=>$user_id]
			];
		}
		

		
		
		$questions = $this->paginate($this->Questions);


        $this->set(compact('questions'));
        $this->set('_serialize', ['questions']);
    }

What it does:
basically if does a different pagnate depending in the user’s role.