Laravel Datatable with json data

Prepare the view with table and javascript

var fx_currency = $('#fx_currency_table').DataTable({
       processing: true,
       serverSide: true,
       bPaginate: true,
       buttons:[],
       ajax: '/fxcurrency',
       columnDefs: [ {
         "targets": 4,
         "orderable": false,
         "searchable": false
         } ]
 });
<div class="card-body">
  <table class="table table-border table-striped" id="fx_currency_table" width="100%>
    <thread>
      <tr>
        <th>Currency Code</th>
        <th>DSP</th>
        <th>Bid</th>
        <th>Ask</th>
        <th>@lang('message.action')</th>
      </tr>
    </thread>
  </table>
</div>

Laravel Controller

 public function index()
     {
         if (!auth()->user()->can('user.view') && !auth()->user()->can('user.create')) {
             abort(403, 'Unauthorized action.');
         }         

         if (request()->ajax()) {
           $business_id = request()->session()->get('user.business_id');
           $fxcurrency = FxCurrency::where('business_id', $business_id)
                       ->select(['currency_code', 'id', 'dsp', 'ask', 'bid']);
 
             return Datatables::of($fxcurrency)
                 ->addColumn(
                     'action',
                     '
                     <button data-href="{{action(\'FxCurrencyController@edit\', [$id])}}" class="btn btn-xs btn-info btn-modal" data-container=".fxcurrency_edit_modal"><i class="fas fa-edit"></i> Edit</button>
                     &nbsp;
    <button data-href="{{action(\'FxCurrencyController@destroy\', [$id])}}" class="btn btn-xs btn-modal btn-info delete_user_button" data-container=".location_edit_modal"><i class="fas fa-trash-alt"></i> Delete</button>
                    ‘
                 )
                 ->removeColumn('id')
                 ->rawColumns([4])
                 ->editColumn('ask', function($fxcurrency) {
                   return $this->util->pack_dsp($fxcurrency->ask, $fxcurrency->dsp);
                 })
                 ->editColumn('bid', function($fxcurrency) {
                   return $this->util->pack_dsp($fxcurrency->bid, $fxcurrency->dsp);
                 })
                 ->make(false)
                 ;
         }
         return view('fx_currency.index');
     } 
Posted in Development | Tagged , , , | Leave a comment

Installing Laravel in OSX

Installing Laravel in OSX is not difficult, just follow the steps below

Install Homebrew

For the latest install command, visit http://brew.sh

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Install PHP with Homebrew

Find PHP 7

brew search php7

Install PHP 7.3

brew install php@7.3

Install mcrypt

brew install mcrypt

Install MySQL

brew install mysql

Install Composer

  1. Visit https://getcomposer.org
  2. Click Download
  3. Run the commands in terminal
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" 
php -r "if (hash_file('sha384', 'composer-setup.php') === '756890a4488ce9024fc62c56153228907f1545c228516cbf63f885e036d37e9a59d27d63f46af1d4d07ee0f76181c7d3') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" 
php composer-setup.php 
php -r "unlink('composer-setup.php');"

Make Composer globally accessible

mv composer.phar /usr/local/bin/composer

Setup new Laravel App

Download laravel installer from composer and make it available globally

composer global require "laravel/installer"

Go to the directory you want to install your app

laravel new laravel-blog

Run a local development server

This will serve the the laravel-blog app at http://localhost:8000

php artisan serve
Posted in Development | Tagged , , | Leave a comment

Backup script with rotation

Found a nice backup script that with daily, weekly monthly rotation
https://github.com/ccztux/glsysbackup

I use this script to backup my work files and kids photos that stored in Synology NAS, below is the configuration that I use. Always have a few copies of kids’ photos something you will never get back.

 
 p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica} p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica; min-height: 14.0px} 
 #---------
 # Logging:
 #---------

 # enable log to file
 # (possible values: 1|0)
 log_to_file="1"
 
 # enable log to stdout
 # (possible values: 1|0)
 log_to_stdout="0"

 # enable log to system logfile
 # (possible values: 1|0)
 log_to_syslog="0"

 # enable log to system journal
 # (possible values: 1|0)
 log_to_journal="0"

 # timestamp format for log messages
 # (HINT: have a look at: 'man strftime')
 log_timestamp_format="%Y-%m-%d %H:%M:%S"

 # truncate logfile at each backup cycle
 # (possible values: 1|0)
 log_to_file_truncate="0"
 
 #------------
 # Privileges:
 #------------
 
 # enable this to check if glsysbackup is running with root privileges
 # (possible values: 1|0)
 root_privileges_required="1"

 #--------
 # Renice:
 #--------
 
 # enable reniceing of glsysbackup and child procs
 # (possible values: 1|0)
 re_nice_enabled="0"
 
 # set renice priority
 # (possible values: -20...19)
 # (HINT: have a look at: 'man renice')
 re_nice_priority="19"
 
 #-----------
 # Re-ionice:
 #-----------
 
 # enable re-ioniceing of glsysbackup and child procs
 # (possible values: 1|0)
 re_ionice_enabled="0"
 
 # set re-ionice scheduling class
 # (possible values: 0|1|2|3)
 # (HINT: have a look at: 'man ionice')
 re_ionice_scheduling_class="2"
 
 # set re-ionice priority
 # (possible values: 0...7)
 # (HINT: have a look at: 'man ionice')
 re_ionice_priority="7"
 
 #----------
 # Rotation:
 #----------
 
 # keep max 1 backup a day
 backup_rotation_one_backup_per_day_only="1"
 
 # enable daily backup rotation
 # (possible values: 1|0)
 backup_rotation_daily_enabled="1"
 
 # number of backup files to keep of daily backups
 backup_rotation_daily_max_backups="14"
 
 # enable weekly backup rotation
 # (possible values: 1|0)
 backup_rotation_weekly_enabled="1"
 
 # rotation weekday for weekly rotation (1 is monday)
 # (possible values: 1|2|3|4|5|6|7)
 backup_rotation_weekly_weekday="1"
 
 # number of backup files to keep of weekly backups
 backup_rotation_weekly_max_backups="8"
 
 # enable monthly backup rotation
 # (possible values: 1|0)
 backup_rotation_monthly_enabled="1"
 
 # rotation day of month for monthly rotation (1 is monday)
 # (possible values: 1|2|3|...|last day of month)
 backup_rotation_monthly_day_of_month="1"
 
 # number of backup files to keep of monthly backups
 backup_rotation_monthly_max_backups="3"
 
 #--------------------
 # Installed packages:
 #--------------------
 
 # enable the creation of installed packages file
 # (possible values: 1|0)
 installed_packages_enabled="0"
 
 # force this package manager to create installed packages file, if you have more than one package
 # manager installed
 # (possible values: rpm|dpkg|pacman|equery|pkgutil)
 installed_packages_forced_manager=""
 
 # path where installed packages file should be created
 installed_packages_directory="/root"
 
 #--------
 # Backup:
 #--------
 
 # if this value is less equal than the tar rc, the backup job will be interpreted
 # as 'backup successful'
 # (possible values: 0|1|2)
 # (HINT: have a look at: 'man tar' section: 'RETURN VALUE')
 backup_successful_tar_rc="1"
 
 # enable backup compression
 # (possible values: 1|0)
 backup_compression_enabled="1"
 
 # backup compression type
 # (possible values: gzip|bzip2|xz|lzip|lzma|lzop)
 backup_compression_type="gzip"
 
 # enable backup verbose mode
 backup_verbose_mode_enabled="1"
 
 # show backup totals
 # (possible values: 1|0)
 backup_show_totals="1"
 
 # individual tar options
 # (HINT: have a look at: 'man tar')
 backup_individual_options=(
 ""
 )
 
 # set backup destination path
 backup_destination_path="/var/backups"
 
 # set backup filename
 backup_base_filename="${script_config_name}"
 
 # files and folders you want to backup
 backup_items=(
 "/volume2/home/"
 "/volume2/photo"
 )
 
 # exclude this items from backup
 # (HINT: have a look at: 'man tar')
 backup_exlude_items=(
 ""
 )

 #------------
 # Encryption:
 #------------
 
 # enable backup encryption with openssl
 # (possible values: 1|0)
 backup_encryption_enabled="0"

 # set password for encryption
 backup_encryption_password="test1234"
 
 #-------------------
 # Pre backup script:
 #-------------------

 # enable pre backup script functionality
 # (possible values: 1|0)
 pre_backup_script_enabled="0"
 
 # path to pre backup script
 pre_backup_script="/home/pi/pre.sh"
 
 # exit glsysbackup in case execution of pre backup script was not successful
 # (possible values: 1|0)
 pre_backup_exit_when_unsuccessful="1"
 
 #--------------------
 # Post backup script:
 #--------------------
 
 # enable post backup script functionality
 # (possible values: 1|0)
 post_backup_script_enabled="0"
 
 # path to post backup script
 post_backup_script="/home/pi/post.sh"
 
 # exit glsysbackup in case execution of post backup script was not successful
 # (possible values: 1|0)
 post_backup_exit_when_unsuccessful="1"
Posted in Development | Tagged , , | Leave a comment

Laravel session storage in redis

Redis provide a better performance compare to file storage for your session driver, the following show how it can be done.

Setting up redis configuration, edit config/database.php,in redis section add session option and adjust database number accordingly.

  'redis' => [
         'client' => env('REDIS_CLIENT', 'phpredis'),

         'options' => [
             'cluster' => env('REDIS_CLUSTER', 'redis'),
             'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
         ],
 
         'default' => [
             'url' => env('REDIS_URL'),
             'host' => env('REDIS_HOST', '127.0.0.1'),
             'password' => env('REDIS_PASSWORD', null),
             'port' => env('REDIS_PORT', 6379),
             'database' => env('REDIS_DB', 0),
         ],
 
         'session' => [
             'url' => env('REDIS_URL'),
             'host'     => env('REDIS_HOST', 'localhost'),
             'password' => env('REDIS_PASSWORD', null),
             'port'     => env('REDIS_PORT', 6379),
             'database' => env('REDIS_CACHE_DB', 1),
         ],
 
         'cache' => [
             'url' => env('REDIS_URL'),
             'host' => env('REDIS_HOST', '127.0.0.1'),
             'password' => env('REDIS_PASSWORD', null),
             'port' => env('REDIS_PORT', 6379),
             'database' => env('REDIS_CACHE_DB', 2),
         ],
 

     ], 

Edit config/session.php to use redis and connect to the defined database

 /*
     |--------------------------------------------------------------------------
     | Default Session Driver
     |--------------------------------------------------------------------------
     |
     | This option controls the default session "driver" that will be used on
     | requests. By default, we will use the lightweight native driver but
     | you may specify any of the other wonderful drivers provided here.
     |
     | Supported: "file", "cookie", "database", "apc",
     |            "memcached", "redis", "dynamodb", "array"
     |
     */

     'driver' => env('SESSION_DRIVER', ‘redis’),   // <-- change from 'file' to 'redis'

/*
     |--------------------------------------------------------------------------
     | Session Database Connection
     |--------------------------------------------------------------------------
     |
     | When using the "database" or "redis" session drivers, you may specify a
     | connection that should be used to manage these sessions. This should
     | correspond to a connection in your database configuration options.
     |
     */
 

     // 'connection' => env('SESSION_CONNECTION', null), <--- comment this
     'connection' => 'session', // <--- add this line 

Now setting is done.

Posted in Development | Tagged , | Leave a comment

Laravel using Flysystem accessing AWS S3 storage

With the package Flysystem, we could easily access files stored in AWS S3

Config

edit the config file in /config/filesystems.php, change the AWS key pair accordingly

Installing Amazon S3 Driver

Before using the S3 storage, package has to be installed with composer

composer require league/flysystem-aws-s3-v3

Accessing Amazon S3 files

use Illuminate\Support\Facades\Storage;

$disk = Storage::disk('s3');

// store file into S3
$disk->put('images/1', $fileContents);

// check file exists?
$exists = $disk->exists('file.jpg');

// get file
$file = $disk->get('file.jpg');

// create a temp url
$url = $disk->temporaryURL('file.jpg', now()->addMinutes(5));

// get file size
$size = $disk->size('file.jpg');

// get last modified
$time = $disk->lastModified('file.jpg');

// delete file
$disk->delete('file.jpg');
Posted in Development | Tagged , , , | Leave a comment