Friday, 12 May 2017

Possible Ways of Naming Route

Calling by giving snake case

Route::resource('patron_profile','Setting\Library\PatronProfileController');
route('patron_profile.index');


Calling by giving an alias


Route::resource('profile','Setting\Library\PatronProfileController',[
          'as' => 'patron'
        ]);
route('patron.profile.index');




Thursday, 11 May 2017

Laravel Query Log - Check Query & Array Pass

Enable Query Log

Laravel can optionally log in memory all queries that have been run for the current request. Be aware that in some cases, such as when inserting a large number of rows, this can cause the application to use excess memory. To enable the log, you may use the enableQueryLog( ) method:

\DB::enableQueryLog();
        Alumni::with('alumni_careers')->findOrFail($id);
        $result = \DB::getQueryLog();
        dump($result);


With the code above , we can check wether the alumni table has relationship with alumni_careers table as define in model class. The output will be like below :









Laravel - Change Date Format


Change Date Time Format (Laravel 5.3 Above)

Below shows how the the default time picker were change into date time format that can be safe into database . This also could be use to display user date into view page.

public function update(Request $request, $id)
{
  $alumni = Alumni::find($id); //retrieve fields from model class
  date('Y-m-d', strtotime($request["dob"])); //change date format to save in database
  $alumni->update($request->except('_token')); //return all request inputs

  \Session::flash('alert-success', 'Profile Successfully Updated'); //session flash
  return redirect(route('profile.index')); //redirect
}



Reference 


http://stackoverflow.com/questions/15567854/warning-date-format-expects-parameter-1-to-be-datetime

Wednesday, 3 May 2017

Topic 17 - Laravel Repository

Introduction


Just to remember laravel repository is not mandatory for laravel projects but represent as collection of specific type of entities where we write those functions and information on interface and then implement them on repositories to provide a cleaner way and easy to read for our controllers and can be used repetitively (over and over) .


Repositories interface --------------- belongs to -----> domain layer
Implementation repositories ------- belongs to ------> application-service layer

Domain Layer 

The domain model layer contains information and functionality related to what it means to be a User. It should map conceptually onto something that exists physically in the real world or a clearly defined concept in the problem space.

Service Layer

The service contains information and functionality related to performing atomic units of work. It should map conceptually onto tasks that are performed on or by members of the Domain model. A single atomic task performed by clicking a button in the application generally involves many members of the Domain working together.

Benefit of Use


1. Using repositories make our controllers less verbose , loosely coupled and easier to read.
2. Represent as concept of storage collection for specific type of entitiy (model)
3. Abstract storage mechanism for authoritative collection of entities.
4. Freedom to swap out data stores at a later date.

Without Repository 

class AlumniController extends Controllers{ public function index(){ $alumni = Alumni:all(); return View::make('alumni.index',compact('alumni')); } public function create(){ return View::make('alumni.create'); } public function show($id){ $alumni=Alumni::find($id); return View::make('alumni.show',compact('alumni')); } }

With Repositories

1: Create the Repository Folder














2: Create class Interface
<?php namespace App\Repositories\Alumni; interface AlumniRepository { public function getAll(); public function show($id); }

3: Create class Repository
<?php namespace App\Repositories\Alumni; use App\Models\Alumni; class EloquentAlumni implements AlumniRepository { private $model; public function __construct(Alumni $model) { $this->model = $model; } public function getAll(){ return Alumni::all(); } public function show($id){ return Alumni::find($id); } }

4: Create Backend Service Provider

<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class BackendServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { // } /** * Register any application services. * * @return void */ public function register() { $this->app->bind('App\Repositories\Alumni\AlumniRepository', 'App\Repositories\Alumni\EloquentAlumni'); } }

5: Update Providers in Config/App.php

'providers' => [ .
. App\Providers\BackendServiceProvider::class, ],

6: Update Your Controller

class AlumniController extends Controller { protected $alumni; public function __construct(AlumniRepository $alumni) { $this->alumni = $alumni; } public function index() { $alumni = $this->alumni->getAll(); // use function index in alumni interface & repository return view('layouts.template',compact('alumni')); } }

References 


http://shawnmc.cool/the-repository-pattern#disqus_thread
http://vegibit.com/laravel-repository-pattern/
http://stackoverflow.com/questions/31453570/laravel-5-repository-inside-service-provider

General - Distinguishing Intel Processor Number

Bootstrap Touchspin

Introduction


Bootstrap Touchspin is something that benefits and easy to use concept when working with value or numeric input . An example below shows how we increase / decrease user salary inside form bootstrap.

<div class="form-group">
    <label class="col-sm-2 control-label" >Salary</label>
    <div class="col-sm-10">
        <input id="demo1" type="text" value="0" class="form-control"           data-min="0" data-step="1.0" data-decimals="2" data-prefix="$" 
          style="display: block;">
    </div>
</div>

Example Script

  <script>
            $("input[name='demo1']").TouchSpin({
                min: 0,
                max: 10000,
                step: 1.0,
                decimals: 2,
                boostat: 5,
                maxboostedstep: 10,
                postfix: '$'
            });
        </script>

The use / meaning 


  • value = initial value to be displayed
  • data-min = minimum data that allowed 
  • data-decimals = shows the number of decimals
  • data-prefix = set the symbol of currency or any logical symbol


Reference 


http://www.virtuosoft.eu/code/bootstrap-touchspin/

Tuesday, 2 May 2017

Datatable Custom Filter

Getting Started


Custom filter is very handy for developers to filtering their data to desired output hence able to provide a report based on a filtering they want. This topic will show the example on how to filter date search inside a datatable . Consistently consist of html , css and javascript accordingly.

HTML

<div class="row">
  <div class="large-6 columns">
    <label for="start">Start Date</label>
    <input id="start" type="date" /><br />
  </div>
  <div class="large-6 columns">
    <label for="end">End Date</label>
    <input id="end" type="date" /><br />
  </div>
</div>
<div class="row">
  <div class="large-12 columns">
    <button class="button radius" id="filter">Filter</button>
    <button id="clearFilter" class="button radius secondary">Clear Filter</button>
  </div>
</div>
<div class="row">
  <div class="large-12 columns">
    <table id="oTable">
      <thead>
        <tr>
          <th>Name</th>
          <th>Date</th>
        </tr>
      </thead>
    </table>
  </div>
</div>

CSS

body {
  padding: 20px;
}
td, th {
  min-width: 300px;
  text-align:left;
}

JAVASCRIPT

$(function(){
  // Basic Setup
  var $tableSel = $('#oTable');
  $tableSel.dataTable({
    'aaData': dummyData,
    'aoColumns': [
      {'mData': 'name'},
      {'mData': 'registered'}
    ],
    'sDom': '' // Hiding the datatables ui
  });
  
  $('#filter').on('click', function(e){
    e.preventDefault();
    var startDate = $('#start').val(),
        endDate = $('#end').val();
    
    filterByDate(1, startDate, endDate); // We call our filter function
    
    $tableSel.dataTable().fnDraw(); // Manually redraw the table after filtering
  });
  
  // Clear the filter. Unlike normal filters in Datatables,
  // custom filters need to be removed from the afnFiltering array.
  $('#clearFilter').on('click', function(e){
    e.preventDefault();
    $.fn.dataTableExt.afnFiltering.length = 0;
    $tableSel.dataTable().fnDraw();
  });
  
});

/* Our main filter function
 * We pass the column location, the start date, and the end date
 */
var filterByDate = function(column, startDate, endDate) {
  // Custom filter syntax requires pushing the new filter to the global filter array
  $.fn.dataTableExt.afnFiltering.push(
      function( oSettings, aData, iDataIndex ) {
       var rowDate = normalizeDate(aData[column]),
              start = normalizeDate(startDate),
              end = normalizeDate(endDate);
          
          // If our date from the row is between the start and end
          if (start <= rowDate && rowDate <= end) {
            return true;
          } else if (rowDate >= start && end === '' && start !== ''){
            return true;
          } else if (rowDate <= end && start === '' && end !== ''){
            return true;
          } else {
            return false;
          }
        }
  );
 };

// converts date strings to a Date object, then normalized into a YYYYMMMDD format (ex: 20131220). Makes comparing dates easier. ex: 20131220 > 20121220
var normalizeDate = function(dateString) {
  var date = new Date(dateString);
  var normalized = date.getFullYear() + '' + (("0" + (date.getMonth() + 1)).slice(-2)) + '' + ("0" + date.getDate()).slice(-2);
  return normalized;
}

// Filler data for demo (thanks to http://json-generator.com)
var dummyData = [
    {
        "name": "Chasity Stanton",
        "registered": "1992-08-12"
    },
    {
        "name": "Mcgowan Vance",
        "registered": "2010-06-25"
    },
    {
        "name": "Craig Hill",
        "registered": "1992-08-11"
    },
    {
        "name": "Lois Elliott",
        "registered": "2003-02-22"
    },
    {
        "name": "Gross Frost",
        "registered": "2005-09-02"
    },
    {
        "name": "Debra Emerson",
        "registered": "2003-05-29"
    },
    {
        "name": "Leona Wilkinson",
        "registered": "1991-01-22"
    },
    {
        "name": "Elena Puckett",
        "registered": "1996-06-21"
    },
    {
        "name": "Mcintosh Hudson",
        "registered": "1992-12-13"
    }
];

Example Output



Reference & Source


https://datatables.net/examples/plug-ins/range_filtering.html
https://codepen.io/markmichon/pen/tmeGD