Creating Plugins

Welcome to Step by Step Plugin creating tutorial where you will learn the basic building of Plugin with very simple few steps. By the end of our tutorials, you should be well on your way to creating your first Plugin from scratch. Today we are going to build a very simple Google Analytics Plugin.

  1. What is Google Analytics ?
  2. Create Plugin Directory
  3. Create Plugin Class
  4. Injecting Google Script to All views
  5. Add link to Admin Panel Settings menu
  6. Create Admin Panel Google Analytics Settings view
  7. Add routes and autoload for our Controller
  8. Create Google Analytics Controller

What is Google Analytics ?

Google Analytics is a web analytics service offered by Google that helps you to track and report website traffic. To integrate google analytics in your website you need to add few lines of JavaScripts in your website pages. You will get the script from your Google Analytic Account. For more information, See Google Analytics

Create Plugin Directory

Every plugin should have its own folder in app/Plugins. So create GoggleAnalyticPlugin directory inside app/Plugins. Directory structure for your GoogleAnalyticPlugin shown below. For more information, See Plugin Directory Structure

  • app
    • Plugins
      • GoogleAnalyticPlugin
        • controllers
          • GoogleAnalyticController.php
        • views
          • settings.blade.php
        • GoogleAnalyticPlugin.php

Create Plugin Class

Create GoogleAnalyticPlugin.php file inside GoogleAnalyticPlugin directory extend App\Components\PluginAbstract class. Before we proceed read Plugin Abstract documentation.



/*

GoogleAnalyticPlugin.php

*/

use App\Components\PluginAbstract;
use App\Components\Plugin;



class GoogleAnalyticPlugin extends PluginAbstract
{
    public function author()
    {
        return 'Author Name';
    }

    public function description()
    {
        return 'This is Google Analytics Plugin that keep tracks of your website traffic.';
    }

    public function version()
    {
        return '0.0.1';
    }

    public function website()
    {
        return 'www.yourwebsite.com';
    }

    public function hooks()
    {
       
       /* All the hooks needed for GoogleAnalyticPlugin will be added here. 
          will see later.
        */
        
    }   

    public function autoload()
    {
        /* GoogleAnalyticController Will be autoloaded here. 
            will see later.
        */

    }

    public function routes() 
    {
        /* GoogleAnalyticController routes Will be added here. 
            will see later.
        */
    }
}  

            

Injecting Google Analytics Script to views

We will add a theme hook to scriptTags hook inside GoogleAnalyticPluign.php hooks() method. For more information, See Theme Hooks and All Theme Hooks lists documentation.


Theme::hook('scriptTags', function () {
    
    /* retriving google analytic key from settings table */
    $google_analytics_key = UtilityRepository::get_setting('google_accountNumber');

    /* inserting key to google analytic script */
    $google_analytics_script = <<<GOOGLE_ANALYTICS_CODE
                
                (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','//www.google-analytics.com/analytics.js','ga');  ga('create','{$google_analytics_key}', 'auto');ga('send', 'pageview');

GOOGLE_ANALYTICS_CODE;
            
    return $google_analytics_script;
});            
            

In the above code taking Google Analytics key from database settings table and adding with Google Analytics Script. Then returning the whole script code to theme view. UtilityRepository::get_setting('google_accountNumber') method() is used to retrive setting values from Settings table or you can use App\Models\Settings::_get(''google_accountNumber'') directly. See Database Models and Repository documentation. If you want you can use your own table too. See Plugin Instalation

In order to add a link into admin panel settings menu we need to use Theme::hook('admin_plugin_menu') like previous hook. See the code below :


Theme::hook('admin_plugin_menu', function () {
        
    /* generating url for menu link*/
    $url = url('/admin/googleAnalyticSettings');

    /* setting title for menu */
    $title = "Google Analytics Setting";

    $link  = <<<ADMIN_MENU_LINK

    <li><a href="{$url}"><i class="fa fa-circle-o"></i>{$title}</a></li>

ADMIN_MENU_LINK;

            
    return $link;
});
            

Create Admin Panel Google Analytics Settings view

Create settings.blade.php in app/Plugins/GoogleAnalyticPlugin/views directory and extend admin master layout @extends('admin.layouts.admin') and some sections. See below code :


@extends('admin.layouts.admin')

@section('content')
        
    @parent
        
    <div class="content-wrapper">
       <!-- Content Header (Page header) -->
       <section class="content-header content-header-custom">
          <h1 class="content-header-head"><!-- Write Your Title Here --></h1>
       </section>
       <!-- Main content -->
       <section class="content">
          <div class="col-md-12 section-first-col">
            
          <!-- add your code html code here  -->


          </div>
        </section>
    </div>

@endsection

@section('scripts')
        
        <!-- add your scripts and styles here -->

@endsection
            

See below code for our GoogleAnalyticPlugin settings.blade.php view code.


@extends('admin.layouts.admin')

@section('content')
        
    @parent
        
    <div class="content-wrapper">
       <!-- Content Header (Page header) -->
       <section class="content-header content-header-custom">
          <h1 class="content-header-head">Google Analytics Settings</h1>
       </section>
       <!-- Main content -->
       <section class="content">
          <div class="col-md-12 section-first-col">
            
           <form method = "POST" id = "set-google-analytic-form">
                {!! csrf_field() !!}
               <div class="col-md-10 add-creditpackage-col admin-create-div">
                  <p class="add-credit-package-text">Add Google Analytic Settings</p>
                  <div class="form-group">
                     <label class="package-label"> Add Google Analytic Key</label>
                     <input type="text" id = "google_accountNumber" placeholder="Google Analytic Account Number" value = "{{{($google_accountNumber)}}}" name = "google_accountNumber" class="form-control  input-border-custom">
                  </div>
                  
                  <button type="button" id = "set-google-analytic-btn" class="btn btn-info btn-addpackage btn-custom">Save</button>
               </div>
            </form>


          </div>
        </section>
    </div>

@endsection

@section('scripts')
        
    <link href="{{{asset('Admin')}}}/css/toastr.css" rel="stylesheet"/>
    <script src="{{{asset('Admin')}}}/js/toastr.js"></script>

    <script>
       
       
        $('#set-google-analytic-btn').click(function(){
            
            var ac_no = $('#google_accountNumber').val();


            var data = $('#set-google-analytic-form').serializeArray();
            $.post("{{{ url('/admin/googleAnalyticSettings') }}}", data, function(response){

                if(response.status == 'success')
                    toastr.success(response.message);
                else if (response.status == 'error')
                    toastr.error(response.message);

            });

        });

       
    </script>
    
    <style type="text/css">
       
        .admin-create-div{
           width : 100%;
        }

        .block-switch{
           margin-left: 108%;
            margin-top: -21px;
        }
        .row {
                background-color: #38414A;
        }
        .section-first-col{
            min-height: 0px;
        }
    <style>

@endsection      
            

To add your own custom assets read Plugin Assets documentation and see also Plugin Installation documentation where to keep the assets folder.

Add routes and autoload for our Controller

To autoload controllers and repositories we need to add few lines code. See Plugin Autoload Here see the below code how to add autoload classes and routes of our GoogleAnalyticController. Add the following code in your GoogleAnalyticPlugin class.


/* adding autoload our GoogleAnalyticsController class */
public function autoload()
{
    return array(
        Plugin::path('GoogleAnalyticPlugin/controllers'),
    );
}            

/* adding routes GoogleAnalyticsController class 
    surrounding by admin middleware so that
 */
public function routes()
{
    
    Route::group(['middleware' => 'admin'], function(){

        //google admin settings view route
        Route::get('/admin/googleAnalyticSettings', 'App\Http\Controllers\GoogleAnalyticController@showSettings');
        Route::post('/admin/googleAnalyticSettings', 'App\Http\Controllers\GoogleAnalyticController@saveSettngs');

    });
}
        

Create Google Analytics Controller

In order to add controller we create GoogleAnalyticController.php file inside app/Plugin/GoogleAnalytic/controllers directory. See above step 2. See the whole controller code below :


<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Components\Plugin;
use Illuminate\Http\Request;
use App\Repositories\Admin\UtilityRepository;


class GoogleAnalyticController extends Controller
{

    /* This methos is used to render admin settings view See Plugin view documentation to know more.*/

    public function showSettings () {
        return Plugin::view('GoogleAnalyticPlugin/settings', [
            'google_accountNumber' => UtilityRepository::get_setting('google_accountNumber')
        ]);
    }

    /* This method is used to save settings key to Settings table 
        This route is called with ajax post request from Google Analytics settings view.
    */
    public function saveSettngs (Request $request) {
        
        try {

            UtilityRepository::set_setting('google_accountNumber', $request->google_accountNumber);

            return response()->json([
                'status' => 'success', 
                'message' => 'Google Analytic Key Saved')]);

        } catch (\Exception $e) {
            
            return response()->json(['status' => 'error', 'message' => 'Failed to save Google Analytics Key.')]);
        }

    }
}



            

UtilityRepository::set_setting('google_accountNumber', $request->google_accountNumber); is used to save google analytics key given from admin into settings table. For more information See Plugin Routes & Controllers documentation.

Conclusion

This was a detailed tutorial of Create Plugin using Using DatingFramework. Whilst we hope We have effectively taught you about the detailed of creating a Plugin. If you want to make your Plugin multilanguage supported then See Plugin Language documentation. Best of luck !