Complete step by step tutorial for Cakephp admin panel-Cakephp admin backend

Spread the love

 

Cakephp Admin Login: Admin panel is a control panel of a web application, from where you can manage your data which can be shown to your users. In this tutorial, I will show you how can we create a CakePHP 3 admin panel in detail and how to implement Cakephp Admin Login in detail.

 

 

What is an Admin Panel?

Lets first see what actually is an admin panel for your web application. Admin panel is a section of your application which is in control of yours. Your visitors and any other person who is not authorized is not able to access your application’s admin panel.

However, if you grant access using credentials then that user will able to login to your admin panel and can modify the website’s data.

So let’s start creating a Cakephp 3 admin panel for our application.

In previous tutorials, we have already seen how to make Cakephp 3 login functionality and Cakephp 3 authentication and authorization of a user.

Here we will use same functionalities but to create the separate Cakephp 3 admin panel.

Now let’s see the steps required to create a Cakephp 3 admin panel.

Don’t worry if you don’t get the steps at first. I will example them in details as you read through in this Cakephp admin login example.

  1. First, create a separate “adminsdatabase table to store your admin users credential data.
  2. Baking AdminsController using Cakephp 3 bake command line.
  3. Bake or create Admin model without prefix, using Cakephp 3 bake command line.
  4. Bake Admin template files using cakephp 3 command line.
  5. Set routing prefix for admin in config/routes.php file.
  6. Add Auth component in AppController.
  7. Adding beforeFilter and isAuthorized methods in AppController.
  8. Adding login, logout and beforeFilter methods in AdminsController.
  9. Adding the setPassword method in Admin Entity file.
  10. Create a login template for admins.
  11. Bake all your other application controllers and templates for admin routing using cakephp bake command.

Don’t get afraid of looking into the steps described above. We will see these steps in details and these are very simple and basic steps to follow.

Step 1: Creating the “admins” database table.

For Cakephp 3 admin panel I have created separate “admin” database table to store admins credential data with the following fields=> id, first_name, last_name,  username, password, password_reset_token, email, role, status, created, modified.

You can add or remove the fields as per your requirements. But few fields like id, email, password are required for this tutorial and I will recommend to also keep a role field in admin table.

Please see below image for fields details and their datatypes.

 

Step 2: Bake AdminsController using Cakephp command-line tool or cake bake tool.

In order to have a separate admin panel, we have to actually create separate MVC for our Admin. So first create a separate AdminsController. This AdminsController will be created in src/Controller/Admin folder, as because of using prefix routing while backing.

Prefix routing and separate admin folder structure will give us clean and maintainable file structure and clean code to use.

To bake AdminsController first go to command prompt and enter a path to your application.

Next use the bake command –

bincake bake controller –prefix admin admins

As you see in the above command we have used “–prefix admin”. This will create an “Admin” folder in src/Controller path and in the Admin folder, AdminsController.php will get created. In the above command, last “admins” tells the bake control to create a controller for an admins database table.

 

Here prefix meaning, I want to use my admin panel using URL with admin prefixed.

Like for an example, I want to access CitiesController’s add action from a URL for an admin panel, then the URL will be

localhost://cakephpapp/admin/cities/add

So all the controllers can be accessed using admin prefix for an admin panel.

Step 3: Bake admin model without prefix.

Next, we have to bake an Admin model. In Cakephp 3, model consists of two files first are Entity file and second is Table file. We can create both the files using cake bake command as follows.

Use bake command for an admin model.

bincake bake model admins

We have not used the prefix for a model class, as it is not required to keep a model in separate prefixed folder structure because these files are never exposed to the users.

Above bake command will create two files – Admin.php in Model/Entity and AdminsTable.php file in Model/Table folder structure.

 

Step 4: Bake Admin template using bake command

Next step is to create template files for a basic CRUD generated in AdminsController.php using a bake command –

bincake bake template –prefix admin admins

This command will create an “Admin” folder for the admins database table. And in “Admin” folder another “Admins” folder with CRUD template files will be created.

Step 5: Set routing prefix for admin in config/routes.php file.

In order to use separate URL for our Cakephp 3 admin panel, we have to define route rules. We have created all controller and template files in admin prefix structure. Also if we want to have separate admin URL we have to define prefix routing in routes.php file.

Go to config/routes.php file and add code for admin prefix routing.

Router::prefix('admin', function ($routes) { // All routes here will be prefixed with `/admin` // And have the prefix => admin route element added. $routes->fallbacks(DashedRoute::class); });

 

 

 

 

Step 6: Adding the Auth component in AppController.

 

 

In this step, we have to add and Auth component in  AppController.php to set authentication for our application for both admins and users.

 

Go to AppController.php and in initialize() method add “$this->loadComponent(‘Auth’);”

 

 

public function initialize()
{
    parent::initialize();

    $this->loadComponent('RequestHandler');
    $this->loadComponent('Flash');
    $this->loadComponent('Auth');
        
}

 

After using the auth component if you try to access any URL control will redirect to login. We will create login functionality and login page in upcoming steps. First, add beforeFilter and isAuthorized methods in AppController.php.

 

 

Step 7: Adding beforeFilter and isAuthorized methods in AppController.

 

 

In AppController add beforeFilter method. beforeFilter method will check all the URL before redirecting. In this method, we will define rules for our admin panel. Add below code in before filter for an admin.

 

 

public function beforeFilter(Event $event)
    {
        parent::beforeFilter($event);
        
        $this->Auth->allow('display');
        
        if ($this->request->prefix == 'admin') 
        {
            $this->viewBuilder()->layout('admin');
            
            $this->Auth->config([
                'authenticate' => [
                    'Form' => [
                        'userModel' => 'Admins',
      'fields' => ['username' => 'email']
                    ],
                ],
                'loginAction' => [
                    'controller' => 'Admins',
                    'action' => 'login'
                ],
                'loginRedirect' => [
                    'controller' => 'Jobs',
                    'action' => 'index'
                ],
                'logoutRedirect' => [
                    'controller' => 'Admins',
                    'action' => 'login',
                ],
                'storage' => [
                    'className' => 'Session',
                    'key' => 'Auth.Admin',               
                ],
                //'unauthorizedRedirect' => $this->referer(),
                'unauthorizedRedirect' => false,
                'authorize' => ['Controller'],
            ]);
            
            
        }
        else
        {
            //Add Auth config for users
        }
    }

 

 As you see in the above code,

 

I have used if condition to first check whether an “admin” is prefixed in URL or not. If the admin is prefixed then we have to use rules defined for admin login.

 

 

In $this->Auth->config,

 

 

'authenticate' => [
                    'Form' => [
                        'userModel' => 'Admins',
          'fields' => ['username' => 'email']
                    ],
                ],

indicates application should use Admins database table and a model to verify admin credentials. We have set “userModel” to “Admins” for this purpose. And set “email” field as default username field. So that while login username will be checked as email using email field.

 

Next loginAction, loginRedirect and logoutRedirect are basic redirections to controller actions.

 

'storage' => [
                'className' => 'Session',
                'key' => 'Auth.Admin',               
             ],

Here storage array tells to use separate Session for admin login so that we can access both users and admins sessions on the same browser.

 

For more details of Auth and login please see my previous tutorials for  Cakephp 3 login functionality and Cakephp 3 authentication and authorization of a user.

 

 

 

Now add isAuthorized method in AppController.php.

 

public function isAuthorized($user = null)
    {
        //Any registered user can accesss public functions
        if(empty($this->request->params['prefix']))
        {
            
            return true;
        }
        
        //Only admins can access admin functions
        if($this->request->params['prefix'] === 'admin')
        {
            
            if(($user['role'] == 2) && ($user['status'] == 1))
            {
                return true;
            }
            return false;
        }
        
        //Default deny
        return false;
    }

 

 

In isAuthorizedmethod, I have set a rule to check the role of a user who wants to login as an admin. I have set a role to “2” for admin. If a user has a role as 2 then he can access the admin panel.

 

 

You can get more information about Cakephp 3 authentication and authorization from the Cakephp 3 official document.

 

Step 9: Adding the setPassword method in Admin Entity file.

 

 

Go to Model/Entity/Admin.php and add below function

 

 

protected function _setPassword($password)
{
    if (strlen($password) > 0) {
       return (newDefaultPasswordHasher)->hash($password);
    }
}

 

 Add use CakeAuthDefaultPasswordHasher; at top of Admin.php file, above the class declaration.

 

Here we have used DefaultPasswordHasher class. This class will hash a password entered in add admin functionality while saving in the admins database table.

Step 10: Create login template for admins.

 

 

In this step go to Template/Admin/Admins folder structure and create new file named login.php as the controller will redirect to login page after adding and Auth component.

 

 

Use below code for the login.php file.

 

 

<div class="admins form">
    <?= $this->Flash->render('auth') ?>
    <?=$this->Form->create() ?>
    <fieldset>
        <legend><?=__('Please enter your username and password') ?></legend>
        <!--<?=$this->Form->input('username') ?>-->
        <?=$this->Form->input('email') ?>
        <?=$this->Form->input('password') ?>
    </fieldset>
    <?=$this->Form->button(__('Login')); ?>
    <?=$this->Form->end() ?>
</div>

 

As you see we have use “email” as a form input instead of username – <?=$this->Form->input(’email’) ?>. This will make application to check for email while admin login.

Add login and logout methods in AdminsController as follows.

 

public function login() 
{
    if ($this->request->is('post')) {
        $user = $this->Auth->identify();
        if ($user) {
            $this->Auth->setUser($user);
            return $this->redirect($this->Auth->redirectUrl());
        }
        $this->Flash->error(__('Invalid username or password.'));
    }
}

public function logout() {
    return $this->redirect($this->Auth->logout());
}

 

 

Step 11: Bake all your other application controllers and templates for admin routing using CakePHP bake command.

 

 

Now in this final step, you need to bake all your other controllers and templates for admin routing and for separate admin methods using same bake commands as we have used for baking AdminsController.php and its CRUD templates.

 

 

For example, if you are having a Cities database table, bake controller and templates for cities table in admin routing folder structure using commands

 

bincake bake controller –prefix admin cities – for the controller

 

bincake bake template–prefix admin cities – for templates

 

 

 

This will create the same folder structure which was created for the Admins table.

 

 

Repeat the same process for all the other tables which you to access via admin panel.

 

 

Now test your application using admin prefix to add an admin and login using your admin credentials.

 

 

While using add admin method for example in my application, using

 

 

URL – localhost/cakephpapp/admin/admins/add

 

 

Control will redirect to login method. So first you have to bypass add method from Auth component to access without login and to add your first admin.

 

 

Go to Controller/Admin/AdminsController.php and add beforeFilter method as follows

 

 

public function beforeFilter(Event $event)
{
    parent::beforeFilter($event);
    $this->Auth->allow('add');
}

 

 

 

Now add new admin user and login using it. And try to access the other controller actions using admin prefix.

 

 

Using this tutorial you can create a simple and basic Cakephp 3 admin panel. Hope this cakephp 3 admin panel example will help you to create the admin panel for your cakephp application.

eTaaps Directory


Spread the love

1 thought on “Complete step by step tutorial for Cakephp admin panel-Cakephp admin backend”

  1. Kindly help , based on your instruction in version 3.8 when i type the following in url I get this

    Error: The layout file AdminLayoutadmin.ctp can not be found or does not exist.

    Also I have to change login.php to login.ctp

    Reply

Leave a Comment