Friday, 23 June 2017

Library Catalog API

List of open API Library that we can use to get catalog information

1. Cambridge University Library




Example of JSON response :

http://www.lib.cam.ac.uk/api/voyager/newtonSearch.cgi?searchArg=MATH%20FOR%20CLINICAL&databases=depfacaedb,depfacfmdb,cambrdgedb,depfacozdb,otherdb,manuscrpdb&format=json

source http://www.lib.cam.ac.uk/api/

2. Hathitrust Bibliographic API ( Deprecated )




Example of JSON response :

https://catalog.hathitrust.org/api/volumes/brief/json/isbn:0030110408

source : https://www.hathitrust.org/bib_api

3. Australia Trove API




Example of JSON response :

http://api.trove.nla.gov.au/result?key=tm85hrrtjr9mk7kp&zone=book&q=isbn:0333337352&encoding=json

source : http://help.nla.gov.au/trove/building-with-trove/api-technical-guide





Library Account

Monday, 19 June 2017

Topic 22 - Generic Repositories ( FilterBy )

Introduction


In java, generic methods and classes enable programmers to specifiy, with a single method declaration, a set of related methods , or with a single class single class declaration , a set of related type, respectively. 

However inside laravel , we can do some generic repositories to filter out based on business logic that we can imply . Such as to extract all data / find specific data of a member inside society.


Repository

  public function filterBy($filter, $joins = NULL, $columns = array('*')) {
        $repository_filter = new RepositoryFilter($this->model, $filter, $joins);

        return $repository_filter->filter()->get($columns);
    }
Repository Filter

class RepositoryFilter {

    /**
    * @var
    */
    private $model;

    /**
    * @var
    */
    private $filter;

    /**
    * @var
    */
    private $join;

    /**
    * @param string $attribute
    * @param int $operator
    * @param mixed $value
    */
    public function __construct($model, $filter, $join)
    {
        $this->setModel($model);
        $this->setFilter($filter);
        $this->setJoin($join);
    }

    public function setModel($model)
    {
        $this->model = $model;
    }

    public function setFilter($filter)
    {
        $filter = collect($filter);
        $filtered = $filter->groupBy('group');

        $this->filter = $filtered->all();
    }

    public function setJoin($join)
    {
        $this->join = $join;
    }

    /**
    * @return \Illuminate\Database\Eloquent\Builder
    * @throws RepositoryFilterException
    */
    public function filter()
    {
        // Generate JOIN clause
        $this->_join();

        // Generate WHERE clause
        $this->_filter();

        return $this->model;
    }

    private function _join()
    {
        if (!empty($this->join)) {
            foreach ($this->join as $class => $type) {
                $model = new $class;
                $join = ($type == TABLE_JOIN_LEFT) ? 'leftJoin' : 'join';

                $this->model->$join($model->getTable(), $this->model->getQuery()->from . '.' . str_singular($model->getTable()) . '_id', '=', $model->getTable() . '.id');
            }
        }
    }

    private function _filter()
    {
        if (!empty($this->filter)) {
            foreach ($this->filter as $group => $filters) {
                if ($group > 0) {
                    $where = ($filters[0]->getLogic() == LOGICAL_OR) ? 'orWhere' : 'where';

                    $this->model->$where(function ($query) use ($filters){
                        foreach ($filters as $filter) {
                            $query = $this->_filterCriteria($filter, $query);
                        }
                    });
                } else {
                    foreach ($filters as $filter) {
                        $this->model = $this->_filterCriteria($filter, $this->model);
                    }
                }
            }
        }
    }

    private function _filterCriteria($filter, $model)
    {
        if (!$filter instanceof Filter) {
            throw new RepositoryFilterException("Class {$this->model()} must be an instance of App\\Repositories\\Eloquent\\Filter");
        }

        if (!empty($filter->getValue()) || $filter->getValue() != '') {
            $where = ($filter->getLogic() == LOGICAL_OR) ? 'orWhere' : 'where';

            switch ($filter->getOperator()) {
                case OPERATOR_EQUAL_TO:
                    if (is_array($filter->getValue())) {
                        $where .= 'In';
                        $model->$where($filter->getAttribute(), $filter->getValue());
                    } else {
                        $model->$where($filter->getAttribute(), '=', $filter->getValue());
                    }

                    break;
                case OPERATOR_GREATER_THAN:
                    $model->$where($filter->getAttribute(), '>', $filter->getValue());

                    break;
                case OPERATOR_LESS_THAN:
                    $model->$where($filter->getAttribute(), '<', $filter->getValue());

                    break;
                case OPERATOR_GREATER_THAN_OR_EQUAL_TO:
                    $model->$where($filter->getAttribute(), '>=', $filter->getValue());

                    break;
                case OPERATOR_LESS_THAN_OR_EQUAL_TO:
                    $model->$where($filter->getAttribute(), '<=', $filter->getValue());

                    break;
                case OPERATOR_NOT_EQUAL_TO:
                    if (is_array($filter->getValue())) {
                        $where .= 'NotIn';
                        $model->$where($filter->getAttribute(), $filter->getValue());
                    } else {
                        $model->$where($filter->getAttribute(), '!=', $filter->getValue());
                    }

                    break;
                case OPERATOR_CONTAIN_PHRASE:
                    $model->$where($filter->getAttribute(), 'like', '%' . $filter->getValue() . '%');

                    break;
                case OPERATOR_START_WITH_PHRASE:
                    $model->$where($filter->getAttribute(), 'like', $filter->getValue() . '%');

                    break;
                case OPERATOR_END_WITH_PHRASE:
                    $model->$where($filter->getAttribute(), 'like', '%' . $filter->getValue());

                    break;
                case OPERATOR_IN_BETWEEN:
                    $where .= 'Between';
                    $model->$where($filter->getAttribute(), $filter->getValue());

                    break;
                case OPERATOR_NOT_IN_BETWEEN:
                    $where .= 'NotBetween';
                    $model->$where($filter->getAttribute(), $filter->getValue());

                    break;
            }
        }

        return $model;
    }

Controller

public function postData(Request $request)
    {
      // Retrieve POST data(request) - to be use in the $filter array
       $patron_name = $request->get('patron');

       $filter = array(
       Filter::create('patrons.name', OPERATOR_CONTAIN_PHRASE, $patron_name),
      );

      // Filter option with target column
      $patron = $this->patron->filterBy($filter);

      // Instantiate Datatable Entity
      $datatables = Datatables::of($patron)
          ->addIndexColumn()
          ->add_column('namelink', function($patron){
            return
            '<a href="' . route('patron.show', $patron->id) .'">'.$patron->name.'</a>';
          })

          ->add_column('statuselection', function($patron){
            return
              $patron->StatusName;
          })

          ->add_column('studentselection', function($patron){
            return
              $patron->student->id_no;
          })

          ->add_column('applicantselection', function($patron){
              if((!empty($patron->libraryProfile->profile_name)) )
              {
                return $patron->libraryProfile->profile_name;
              }
          })
          ->add_column('action', function ($patron){
              return
              Form::iconUpdate(route('patron.edit', $patron->id))." ".
              Form::iconDelete(route('patron.destroy', $patron->id))." ";
          })
          ->rawColumns(['action','namelink','programselection','statuselection','applicantselection']);


          return $datatables->make(true);
    }

View

<script>

  var table = $('#patron-table').DataTable({
        {!! Config::get('datatable.setting') !!}
        ajax: {
          url: '{!! url("library/patron/data") !!}',
          method: 'POST',
          headers: {
              'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
          },
          data: function (d) {
                d.patron = $('input[name="patron"]').val();
                // d.patron_applicant = $('#patron_applicant').val();
                // d.patron_status = $('#patron_status').val();
          },
          error: function(data){
              // Error...
              var errors = data.responseJSON;
              $('html').html(data.responseText);
              console.log(data.responseText);
          }
        },
        columns: [
          { sTitle: 'No' , data:'DT_Row_Index', width: '5%' },
          { sTitle: 'Name', data: 'namelink', name:'name' , width: '15%'}, //data is database name // name is modelName for relationship
          { sTitle: 'ID Number', data: 'studentselection' , width: '10%' }, //data is database name // name is modelName for relationship
          { sTitle: 'Profile', data: 'applicantselection' , width: '10%'}, //data is database name // name is modelName for relationship
          { sTitle: 'Status', data: 'statuselection' , width: '10%'},
          { sTitle: 'Action', data: 'action', width: '10%'},
        ]
    });

    $('#B3-filter-box').on('submit', function(e) {
        table.draw();
        e.preventDefault();
    });

</script>





Friday, 16 June 2017

Laravel : Database Migration ( Key Constraint )

Database Migration

What are steps to be looked from cli command "php artisan migrate:refresh --seed" . First of as we this command will drop table migration from bottom to top . However in our case, we should declare a foreign key migration table exactly at bottom of the folder. This is to ensure we can drop child key and the relation of foreign key with another table before dropping parent keys.


DropForeign ( ) need to be call under Schema::table and with a blue print object


Schema::table('courses', function (Blueprint $table) {
        $table->dropForeign('courses_post_id_foreign');    
});

or


Schema::table('courses', function (Blueprint $table) {        
       $table->dropForeign(['your_key_name']);
});

Next, after removing the relation and the key constraint of foreign key. Now we can drop the column inside the class table .


   Schema::table('courses', function (Blueprint $table) {
         $table->dropForeign('courses_blocks_idx_1');
         $table->dropColumn('faculty_id');
       });

References :

https://stackoverflow.com/questions/41416993/call-to-undefined-method-illuminate-database-schema-mysqlbuilderdropforeign

https://laravel.com/docs/5.4/migrations

Tuesday, 13 June 2017

Changing Input Name Using JQuery

Today's lesson is to change input name based on form drop down type when on change function triggered.


Form 
<div class="form-group">
    <label class="col-lg-2 control-label">Material Type</label>
    <div class="col-lg-6">
          {!! Form::Dropdown('material_type', $typeselection, (!empty($profile->material_type)) ? $profile->material_type : '','id="repeat-frequency" required') !!}
    </div>
  </div>

  <div class="form-group required">
    <label class="col-lg-2 control-label">Borrowing Period</label>
    <div class="col-lg-6">
      <div class="input-group">
        <input id="borrow" name="borrow_period" type="number" min="0" class="form-control" placeholder="" value="{{ old('borrow_period',  isset($profile->borrow_period) ? $profile->borrow_period : null) }}" required>
        <span class="input-group-addon">Days</span>
      </div>
    </div>
  </div>

JQuery
<script type="text/javascript">
  $( document ).ready(function() {

    $('#repeat-frequency').on('change', function(){
      var frequency = $('#repeat-frequency').val();
      if(frequency == 1 ){
        $('#repeat-every').text("Maximum Books");
        //option 1 select id
        document.getElementById("borrow").setAttribute('name', 'borrow_book');
      } else if (frequency == 2){
        $('#repeat-every').text("Maximum CD/DVD");
        //option 2 select id
        $('#borrow').attr("name","borrow_cd");
    });

  });
</script>

Friday, 9 June 2017

Syncing Blogger or Import Blogger to Disqus

Centralized your feedback with Disqus.com


Step 1 : Get Started





Step 2 : Install Disqus




Step 3 :  Create Your Disqus Url




Step 4 : Select your plan




Step 5 : Choose your platform to deploy





Step 6 : Add Disqus to your site / Import from your site




Step 7 : Choose your blog



Step 8 : Enable Syncing 




Step 9 : Our Result






Thursday, 8 June 2017

Topic 21 - Laravel Accessor & Mutator

Accessor 

An access function which can be implant inside of our model . For java, we called gettor. Below shows the example of Program Name with the return the string value if were match.
  public function getProgramNameAttribute()
  {
      if ($this->program == '1') {
        return 'Bachelor of Business Admin';
      }
      else if ($this->program == '2') {
        return 'Bachelor of Pure Math';
      }
      else if ($this->program == '3') {
        return 'Bachelor of Computer Science';
      }
  }


Mutator  

A function that set our attribute to the value of . For java, we called settor. Below shows the example of a function that set the attribute program name into the value we wan.
 public function setProgramNameAttribute($value)
  {
      $this->program = strtolower($value)
  }

Topic 20 - Applying Carbon (DateTime)

Carbon is a package helper that help developers to write and manage logic date inside controller and model . It also helps to manipulate by adding and substracting date from insert date.

Example of use :

Model :

    public function getDueDateAttribute()
    {
       return Carbon::parse($this->check_out)->addDays(7);

    }

    public function getDiffDaysAttribute()
    {
       return $this->DueDate->diffInDays(Carbon::now());
    }

Inside the accessor method , field check_out are being called and manipulate by Carbon class. The first function are to return due date of the book which is within next 7 days. While the second function is to count the different days between current day and the due date should be submitted. 


More in carbon , check this link.

References 


https://scotch.io/tutorials/easier-datetime-in-laravel-and-php-with-carbon




Friday, 2 June 2017

Eloquent : Pluck ( Documentation )

When to use ? 

We ever wonder in form selection or dropdown we need to get field 'name' from other table .
Example situation . Each patron should has one patron profile that is in our modal patron we should use belongsTo function whereby patron profile should use hasMany function since one patron profile can have many patrons.

In our form selection we should consider pass the table name with eloquent pluck from our controller. However we need to remind the only thing should be save when using pluck is "ID". Here is the example :


Controller

 $data = array(
          'breadcrumb' => array('Setting', 'Library' ,'Create Patron Profile'),
          'submenu' => 'setting.library.library_navbar',
          'content' => 'setting.library.patronprofile.form',
          'title' => 'Profile Form',
          'settingtitle' => 'Library',
          'toggle' => 'patron_profile',
          'typeselection' => $typeselection,
          'profileselection' => ProfileSetting::pluck('name', 'id')->all(),
          'subjectselection' => $subjectselection,
          'type' => 1,
      );
      return view('layouts.setting_template')->with($data);

View

        {!! Form::MultiDropdown('profile_id', $profileselection, (!empty($patron->profile_id)) ? $patron->profile_id: '','class="select2-form" required') !!}